diff --git a/404.html b/404.html index d5d5b45289..3edc0e052f 100644 --- a/404.html +++ b/404.html @@ -12,13 +12,13 @@ - +
Skip to main content

Page Not Found

We could not find what you were looking for.

Please contact the owner of the site that linked you to the original URL and let them know their link is broken.

- + \ No newline at end of file diff --git a/assets/js/01fe3043.54b21c3a.js b/assets/js/01fe3043.3d1b7f71.js similarity index 99% rename from assets/js/01fe3043.54b21c3a.js rename to assets/js/01fe3043.3d1b7f71.js index 2c7b5e9b9f..0297846428 100644 --- a/assets/js/01fe3043.54b21c3a.js +++ b/assets/js/01fe3043.3d1b7f71.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3343],{7128:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-5.0/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/5.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/laravel-package.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-5.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/5.0/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3343],{7128:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-5.0/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/5.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/laravel-package.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-5.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/5.0/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/029c6d75.f1bed900.js b/assets/js/029c6d75.65a906c8.js similarity index 99% rename from assets/js/029c6d75.f1bed900.js rename to assets/js/029c6d75.65a906c8.js index 9aa0cfaa07..719b5fef79 100644 --- a/assets/js/029c6d75.f1bed900.js +++ b/assets/js/029c6d75.65a906c8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1021],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},858:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.2/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.2/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/symfony-bundle-advanced.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-4.2/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.2/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/4.2/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1021],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},858:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.2/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.2/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/symfony-bundle-advanced.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-4.2/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.2/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/4.2/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/02c5a8b1.f63b8f0a.js b/assets/js/02c5a8b1.91aeeb5a.js similarity index 98% rename from assets/js/02c5a8b1.f63b8f0a.js rename to assets/js/02c5a8b1.91aeeb5a.js index d9357a4a0c..e159218e0c 100644 --- a/assets/js/02c5a8b1.f63b8f0a.js +++ b/assets/js/02c5a8b1.91aeeb5a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[755],{1497:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-6.1/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/symfony-bundle.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/getting-started"},next:{title:"Laravel package",permalink:"/docs/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-6.1/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/symfony-bundle.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/getting-started"},next:{title:"Laravel package",permalink:"/docs/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-4.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/implementing-security.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},sidebar:"version-4.0/docs",previous:{title:"Fine grained security",permalink:"/docs/4.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.0/query-plan"}},u={},c=[],l={toc:c},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6130],{20:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-4.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/implementing-security.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},sidebar:"version-4.0/docs",previous:{title:"Fine grained security",permalink:"/docs/4.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.0/query-plan"}},u={},c=[],l={toc:c},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0370fbfb.479939cf.js b/assets/js/0370fbfb.11bb62db.js similarity index 99% rename from assets/js/0370fbfb.479939cf.js rename to assets/js/0370fbfb.11bb62db.js index 13c65f258d..1ce55d7ab4 100644 --- a/assets/js/0370fbfb.479939cf.js +++ b/assets/js/0370fbfb.11bb62db.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8593],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var r=n(7294),a=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var r=n(7462),a=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),u=n(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:r,default:a}}=e;return{value:t,label:n,attributes:r,default:a}}))}function d(e){const{values:t,children:n}=e;return(0,a.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const r=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(r.location.search);t.set(o,e),r.replace({...r.location,search:t.toString()})}),[o,r])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:r}=e,o=d(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=n.find((e=>e.default))??n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:r}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,o]=(0,u.Nk)(n);return[r,(0,a.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:r}),f=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),y(e)}),[c,y,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=u.indexOf(t),r=c[n].value;r!==l&&(p(t),s(r))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=u.indexOf(e.currentTarget)+1;t=u[n]??u[0];break}case"ArrowLeft":{const n=u.indexOf(e.currentTarget)-1;t=u[n]??u[u.length-1];break}}t?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:r}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,a.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=y(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},a.createElement(b,(0,r.Z)({},e,t)),a.createElement(w,(0,r.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return a.createElement(k,(0,r.Z)({key:String(t)},e))}},9390:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>c});var r=n(7462),a=(n(7294),n(3905));n(1839),n(4866),n(5162);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},i=void 0,l={unversionedId:"other-frameworks",id:"version-6.1/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-6.1/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/other-frameworks.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/universal-service-providers"},next:{title:"Queries",permalink:"/docs/queries"}},s={},c=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],u={toc:c},p="wrapper";function d(e){let{components:t,...n}=e;return(0,a.kt)(p,(0,r.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"installation"},"Installation"),(0,a.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,a.kt)("h2",{id:"requirements"},"Requirements"),(0,a.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,a.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.kt)("p",null,"GraphQLite relies on the ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,a.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,a.kt)("h2",{id:"integration"},"Integration"),(0,a.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,a.kt)("p",null,"You can now use this schema with ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,a.kt)("p",null,"The ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,a.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,a.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,a.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,a.kt)("p",null,"The smallest working example using no framework is:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,a.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,a.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,a.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,a.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,a.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,a.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,a.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n")),(0,a.kt)("h3",{id:"example"},"Example"),(0,a.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,a.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,a.kt)("p",null,"Here we are initializing a Zend ",(0,a.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,a.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,a.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,a.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,a.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new LazyContainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,a.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8593],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var r=n(7294),a=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var r=n(7462),a=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),u=n(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:r,default:a}}=e;return{value:t,label:n,attributes:r,default:a}}))}function d(e){const{values:t,children:n}=e;return(0,a.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const r=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(r.location.search);t.set(o,e),r.replace({...r.location,search:t.toString()})}),[o,r])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:r}=e,o=d(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=n.find((e=>e.default))??n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:r}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,o]=(0,u.Nk)(n);return[r,(0,a.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:r}),f=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),y(e)}),[c,y,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=u.indexOf(t),r=c[n].value;r!==l&&(p(t),s(r))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=u.indexOf(e.currentTarget)+1;t=u[n]??u[0];break}case"ArrowLeft":{const n=u.indexOf(e.currentTarget)-1;t=u[n]??u[u.length-1];break}}t?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:r}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,a.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=y(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},a.createElement(b,(0,r.Z)({},e,t)),a.createElement(w,(0,r.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return a.createElement(k,(0,r.Z)({key:String(t)},e))}},9390:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>c});var r=n(7462),a=(n(7294),n(3905));n(1839),n(4866),n(5162);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},i=void 0,l={unversionedId:"other-frameworks",id:"version-6.1/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-6.1/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/other-frameworks.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/universal-service-providers"},next:{title:"Queries",permalink:"/docs/queries"}},s={},c=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],u={toc:c},p="wrapper";function d(e){let{components:t,...n}=e;return(0,a.kt)(p,(0,r.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"installation"},"Installation"),(0,a.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,a.kt)("h2",{id:"requirements"},"Requirements"),(0,a.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,a.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.kt)("p",null,"GraphQLite relies on the ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,a.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,a.kt)("h2",{id:"integration"},"Integration"),(0,a.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,a.kt)("p",null,"You can now use this schema with ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,a.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,a.kt)("p",null,"The ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,a.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,a.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,a.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,a.kt)("p",null,"The smallest working example using no framework is:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,a.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,a.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,a.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,a.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,a.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,a.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,a.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n")),(0,a.kt)("h3",{id:"example"},"Example"),(0,a.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,a.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,a.kt)("p",null,"Here we are initializing a Zend ",(0,a.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,a.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,a.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,a.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,a.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new LazyContainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,a.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/03abab96.bb40fac9.js b/assets/js/03abab96.fb3893ea.js similarity index 98% rename from assets/js/03abab96.bb40fac9.js rename to assets/js/03abab96.fb3893ea.js index b98424ab3f..ff0aaa18d6 100644 --- a/assets/js/03abab96.bb40fac9.js +++ b/assets/js/03abab96.fb3893ea.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3709],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",b.tabList)},r.createElement(y,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5280:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/docs/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/next/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/autowiring.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/next/type-mapping"},next:{title:"Extending a type",permalink:"/docs/next/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3709],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",b.tabList)},r.createElement(y,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5280:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/docs/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/next/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/autowiring.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/next/type-mapping"},next:{title:"Extending a type",permalink:"/docs/next/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/05e8cfc0.b6e1e919.js b/assets/js/05e8cfc0.b86474cb.js similarity index 96% rename from assets/js/05e8cfc0.b6e1e919.js rename to assets/js/05e8cfc0.b86474cb.js index ccb0e424cf..a3b163331d 100644 --- a/assets/js/05e8cfc0.b6e1e919.js +++ b/assets/js/05e8cfc0.b86474cb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2650],{9767:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},l=void 0,i={unversionedId:"query-plan",id:"version-4.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.0/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/query_plan.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"}},u={},s=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:s},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2650],{9767:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},l=void 0,i={unversionedId:"query-plan",id:"version-4.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.0/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/query_plan.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"}},u={},s=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:s},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/05fed6b1.696ddfac.js b/assets/js/05fed6b1.38feeb95.js similarity index 99% rename from assets/js/05fed6b1.696ddfac.js rename to assets/js/05fed6b1.38feeb95.js index 39bb30fb36..ab92a8b1f0 100644 --- a/assets/js/05fed6b1.696ddfac.js +++ b/assets/js/05fed6b1.38feeb95.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7334],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8316:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-4.2/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.2/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.2/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/autowiring.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-4.2/docs",previous:{title:"Type mapping",permalink:"/docs/4.2/type-mapping"},next:{title:"Extending a type",permalink:"/docs/4.2/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7334],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8316:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-4.2/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.2/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.2/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/autowiring.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-4.2/docs",previous:{title:"Type mapping",permalink:"/docs/4.2/type-mapping"},next:{title:"Extending a type",permalink:"/docs/4.2/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/07623f9a.ebdfb4d1.js b/assets/js/07623f9a.23924493.js similarity index 98% rename from assets/js/07623f9a.ebdfb4d1.js rename to assets/js/07623f9a.23924493.js index 1a9ecf88bb..fc34986ce1 100644 --- a/assets/js/07623f9a.ebdfb4d1.js +++ b/assets/js/07623f9a.23924493.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4009],{4030:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-4.0/docs",previous:{title:"Getting Started",permalink:"/docs/4.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.0/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],d={toc:s},c="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Now, go to the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,r.kt)("p",null,"More advanced parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-4.0/docs",previous:{title:"Getting Started",permalink:"/docs/4.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.0/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],d={toc:s},c="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Now, go to the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,r.kt)("p",null,"More advanced parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>s,metadata:()=>i,toc:()=>h});var r=n(7462),a=(n(7294),n(3905));n(1839);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},o=void 0,i={unversionedId:"prefetch-method",id:"version-4.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.0/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/prefetch_method.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},sidebar:"version-4.0/docs",previous:{title:"Query plan",permalink:"/docs/4.0/query-plan"},next:{title:"File uploads",permalink:"/docs/4.0/file-uploads"}},l={},h=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],p={toc:h},d="wrapper";function c(e){let{components:t,...n}=e;return(0,a.kt)(d,(0,r.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"the-problem"},"The problem"),(0,a.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.kt)("p",null,"A naive implementation will do this:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,a.kt)("a",{parentName:"p",href:"/docs/4.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,a.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')),(0,a.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,a.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,a.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')),(0,a.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1464],{49:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>s,metadata:()=>i,toc:()=>h});var r=n(7462),a=(n(7294),n(3905));n(1839);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},o=void 0,i={unversionedId:"prefetch-method",id:"version-4.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.0/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/prefetch_method.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},sidebar:"version-4.0/docs",previous:{title:"Query plan",permalink:"/docs/4.0/query-plan"},next:{title:"File uploads",permalink:"/docs/4.0/file-uploads"}},l={},h=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],p={toc:h},d="wrapper";function c(e){let{components:t,...n}=e;return(0,a.kt)(d,(0,r.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"the-problem"},"The problem"),(0,a.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.kt)("p",null,"A naive implementation will do this:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,a.kt)("a",{parentName:"p",href:"/docs/4.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,a.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')),(0,a.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,a.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,a.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')),(0,a.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/077a13b8.dc86dbd0.js b/assets/js/077a13b8.575a51af.js similarity index 99% rename from assets/js/077a13b8.dc86dbd0.js rename to assets/js/077a13b8.575a51af.js index b9e2067d17..19cdc5eab4 100644 --- a/assets/js/077a13b8.dc86dbd0.js +++ b/assets/js/077a13b8.575a51af.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5320],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},440:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-5.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/5.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/extend-input-type.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-5.0/docs",previous:{title:"Custom argument resolving",permalink:"/docs/5.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/5.0/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5320],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},440:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-5.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/5.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/extend-input-type.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-5.0/docs",previous:{title:"Custom argument resolving",permalink:"/docs/5.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/5.0/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/079b0d3e.0ae9d1bd.js b/assets/js/079b0d3e.d4aa9ead.js similarity index 99% rename from assets/js/079b0d3e.0ae9d1bd.js rename to assets/js/079b0d3e.d4aa9ead.js index a3e1e889f2..9e5af3f729 100644 --- a/assets/js/079b0d3e.0ae9d1bd.js +++ b/assets/js/079b0d3e.d4aa9ead.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3189],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},918:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-6.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-6.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/6.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/external-type-declaration.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/6.0/extend-type"},next:{title:"Input types",permalink:"/docs/6.0/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/6.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3189],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},918:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-6.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-6.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/6.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/external-type-declaration.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/6.0/extend-type"},next:{title:"Input types",permalink:"/docs/6.0/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/6.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/07c49ebd.337a9957.js b/assets/js/07c49ebd.e45a8e99.js similarity index 99% rename from assets/js/07c49ebd.337a9957.js rename to assets/js/07c49ebd.e45a8e99.js index 02b7b41da4..1a2bfbd4cb 100644 --- a/assets/js/07c49ebd.337a9957.js +++ b/assets/js/07c49ebd.e45a8e99.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[120],{5847:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.1/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/field_middlewares.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},sidebar:"version-4.1/docs",previous:{title:"Custom types",permalink:"/docs/4.1/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.1/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[120],{5847:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.1/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/field_middlewares.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},sidebar:"version-4.1/docs",previous:{title:"Custom types",permalink:"/docs/4.1/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.1/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/085c135f.d10ad352.js b/assets/js/085c135f.eed3a49c.js similarity index 99% rename from assets/js/085c135f.d10ad352.js rename to assets/js/085c135f.eed3a49c.js index dd48c0449e..d63cb340ea 100644 --- a/assets/js/085c135f.d10ad352.js +++ b/assets/js/085c135f.eed3a49c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7128],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6600:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-4.3/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.3/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.3/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/README.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.3/docs",next:{title:"Getting Started",permalink:"/docs/4.3/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7128],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6600:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-4.3/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.3/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.3/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/README.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.3/docs",next:{title:"Getting Started",permalink:"/docs/4.3/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/08fe23a4.b4d430d0.js b/assets/js/08fe23a4.6a618c2f.js similarity index 93% rename from assets/js/08fe23a4.b4d430d0.js rename to assets/js/08fe23a4.6a618c2f.js index f411b9b24b..879eb1e394 100644 --- a/assets/js/08fe23a4.b4d430d0.js +++ b/assets/js/08fe23a4.6a618c2f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4196],{855:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={unversionedId:"mutations",id:"version-6.1/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-6.1/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/mutations.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Type mapping",permalink:"/docs/type-mapping"}},u={},d=[],p={toc:d},l="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(l,(0,a.Z)({},p,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4196],{855:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={unversionedId:"mutations",id:"version-6.1/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-6.1/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/mutations.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Type mapping",permalink:"/docs/type-mapping"}},u={},d=[],p={toc:d},l="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(l,(0,a.Z)({},p,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0a57d896.96ab7e2e.js b/assets/js/0a57d896.6c31eb99.js similarity index 99% rename from assets/js/0a57d896.96ab7e2e.js rename to assets/js/0a57d896.6c31eb99.js index 687cbb61dd..163a9fde04 100644 --- a/assets/js/0a57d896.96ab7e2e.js +++ b/assets/js/0a57d896.6c31eb99.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3024],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},1448:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.1/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.1/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/error_handling.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.1/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.1/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3024],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},1448:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.1/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.1/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/error_handling.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.1/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.1/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0cb7e976.546f70c1.js b/assets/js/0cb7e976.dc857927.js similarity index 99% rename from assets/js/0cb7e976.546f70c1.js rename to assets/js/0cb7e976.dc857927.js index ab8f31e5a3..da9ec3d7c7 100644 --- a/assets/js/0cb7e976.546f70c1.js +++ b/assets/js/0cb7e976.dc857927.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5244],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},5796:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/docs/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/next/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/fine-grained-security.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/next/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/next/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5244],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},5796:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/docs/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/next/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/fine-grained-security.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/next/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/next/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0d7bb119.b55f86b3.js b/assets/js/0d7bb119.f432e9d0.js similarity index 98% rename from assets/js/0d7bb119.b55f86b3.js rename to assets/js/0d7bb119.f432e9d0.js index a527e2ebd9..62eda4bc35 100644 --- a/assets/js/0d7bb119.b55f86b3.js +++ b/assets/js/0d7bb119.f432e9d0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7304],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8396:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.2/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.2/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.2/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/query-plan.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-4.2/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.2/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.2/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7304],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8396:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.2/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.2/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.2/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/query-plan.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-4.2/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.2/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.2/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0db009bb.7ccddee0.js b/assets/js/0db009bb.722111a0.js similarity index 94% rename from assets/js/0db009bb.7ccddee0.js rename to assets/js/0db009bb.722111a0.js index 600d40dd86..e85544f69c 100644 --- a/assets/js/0db009bb.7ccddee0.js +++ b/assets/js/0db009bb.722111a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7622],{6505:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.3/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.3/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.3/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/getting-started.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.3/docs",previous:{title:"GraphQLite",permalink:"/docs/4.3/"},next:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7622],{6505:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.3/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.3/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.3/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/getting-started.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.3/docs",previous:{title:"GraphQLite",permalink:"/docs/4.3/"},next:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0db959c8.6a4091ca.js b/assets/js/0db959c8.8dedaa56.js similarity index 99% rename from assets/js/0db959c8.6a4091ca.js rename to assets/js/0db959c8.8dedaa56.js index 3700a067a3..4adc3745bf 100644 --- a/assets/js/0db959c8.6a4091ca.js +++ b/assets/js/0db959c8.8dedaa56.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[781],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},970:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-5.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-5.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/5.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/doctrine-annotations-attributes.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-5.0/docs",previous:{title:"Migrating",permalink:"/docs/5.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/5.0/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[781],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},970:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-5.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-5.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/5.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/doctrine-annotations-attributes.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-5.0/docs",previous:{title:"Migrating",permalink:"/docs/5.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/5.0/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0df2ba32.6358bf74.js b/assets/js/0df2ba32.2ce34e95.js similarity index 97% rename from assets/js/0df2ba32.6358bf74.js rename to assets/js/0df2ba32.2ce34e95.js index 107c2171ad..4319d14005 100644 --- a/assets/js/0df2ba32.6358bf74.js +++ b/assets/js/0df2ba32.2ce34e95.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8410],{5986:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-4.3/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-4.3/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.3/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/semver.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-4.3/docs",previous:{title:"Annotations reference",permalink:"/docs/4.3/annotations-reference"},next:{title:"Changelog",permalink:"/docs/4.3/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8410],{5986:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-4.3/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-4.3/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.3/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/semver.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-4.3/docs",previous:{title:"Annotations reference",permalink:"/docs/4.3/annotations-reference"},next:{title:"Changelog",permalink:"/docs/4.3/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0e5befdb.caccf97e.js b/assets/js/0e5befdb.47cf4738.js similarity index 98% rename from assets/js/0e5befdb.caccf97e.js rename to assets/js/0e5befdb.47cf4738.js index 9014cc58cc..65d10f27c2 100644 --- a/assets/js/0e5befdb.caccf97e.js +++ b/assets/js/0e5befdb.47cf4738.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4868],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=p(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},i,{className:(0,l.Z)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},5846:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>p,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const l={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},i=void 0,o={unversionedId:"extend-type",id:"version-6.1/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-6.1/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/extend-type.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/autowiring"},next:{title:"External type declaration",permalink:"/docs/external-type-declaration"}},s={},u=[],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4868],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=p(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},i,{className:(0,l.Z)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},5846:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>p,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const l={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},i=void 0,o={unversionedId:"extend-type",id:"version-6.1/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-6.1/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/extend-type.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/autowiring"},next:{title:"External type declaration",permalink:"/docs/external-type-declaration"}},s={},u=[],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0ef60658.e92e1537.js b/assets/js/0ef60658.a3f086b4.js similarity index 99% rename from assets/js/0ef60658.e92e1537.js rename to assets/js/0ef60658.a3f086b4.js index dc0c1d59ea..4caf00392a 100644 --- a/assets/js/0ef60658.e92e1537.js +++ b/assets/js/0ef60658.a3f086b4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1333],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},7258:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-4.2/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.2/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/4.2/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/external-type-declaration.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-4.2/docs",previous:{title:"Extending a type",permalink:"/docs/4.2/extend-type"},next:{title:"Input types",permalink:"/docs/4.2/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.2/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1333],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},7258:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-4.2/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.2/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/4.2/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/external-type-declaration.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-4.2/docs",previous:{title:"Extending a type",permalink:"/docs/4.2/extend-type"},next:{title:"Input types",permalink:"/docs/4.2/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.2/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0fd21208.9194365d.js b/assets/js/0fd21208.9945be0b.js similarity index 96% rename from assets/js/0fd21208.9194365d.js rename to assets/js/0fd21208.9945be0b.js index b6fe7c4ef6..b20afbe4eb 100644 --- a/assets/js/0fd21208.9194365d.js +++ b/assets/js/0fd21208.9945be0b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6595],{4106:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,r={unversionedId:"mutations",id:"version-4.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/mutations.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-4.0/docs",previous:{title:"Queries",permalink:"/docs/4.0/queries"},next:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(p,(0,a.Z)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6595],{4106:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,r={unversionedId:"mutations",id:"version-4.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/mutations.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-4.0/docs",previous:{title:"Queries",permalink:"/docs/4.0/queries"},next:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(p,(0,a.Z)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/102de343.9511b5c5.js b/assets/js/102de343.dc005dfe.js similarity index 99% rename from assets/js/102de343.9511b5c5.js rename to assets/js/102de343.dc005dfe.js index 417f33a9f6..fe7cd8a3dd 100644 --- a/assets/js/102de343.9511b5c5.js +++ b/assets/js/102de343.dc005dfe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3755],{9242:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.1/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.1/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/argument_resolving.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},sidebar:"version-4.1/docs",previous:{title:"Custom annotations",permalink:"/docs/4.1/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.1/extend_input_type"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},d="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3755],{9242:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.1/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.1/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/argument_resolving.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},sidebar:"version-4.1/docs",previous:{title:"Custom annotations",permalink:"/docs/4.1/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.1/extend_input_type"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},d="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/107b7a36.7ecba4f1.js b/assets/js/107b7a36.47f69cda.js similarity index 98% rename from assets/js/107b7a36.7ecba4f1.js rename to assets/js/107b7a36.47f69cda.js index f57882edef..164aa21c00 100644 --- a/assets/js/107b7a36.7ecba4f1.js +++ b/assets/js/107b7a36.47f69cda.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5775],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1526:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-6.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-6.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/6.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/query-plan.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/6.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/6.0/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5775],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1526:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-6.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-6.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/6.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/query-plan.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/6.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/6.0/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/107d11ee.67dc97d7.js b/assets/js/107d11ee.6c98fe0c.js similarity index 97% rename from assets/js/107d11ee.67dc97d7.js rename to assets/js/107d11ee.6c98fe0c.js index bd25831d51..5ee7c615de 100644 --- a/assets/js/107d11ee.67dc97d7.js +++ b/assets/js/107d11ee.6c98fe0c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7472],{5850:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-6.0/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-6.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/6.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/universal-service-providers.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/6.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/6.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7472],{5850:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-6.0/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-6.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/6.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/universal-service-providers.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/6.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/6.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/136c1ee9.8a420157.js b/assets/js/136c1ee9.40baeed2.js similarity index 99% rename from assets/js/136c1ee9.8a420157.js rename to assets/js/136c1ee9.40baeed2.js index 0c4ba7a0f2..b2f3588353 100644 --- a/assets/js/136c1ee9.8a420157.js +++ b/assets/js/136c1ee9.40baeed2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6178],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},3891:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-4.2/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.2/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.2/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/validation.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-4.2/docs",previous:{title:"Error handling",permalink:"/docs/4.2/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.2/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6178],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},3891:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-4.2/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.2/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.2/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/validation.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-4.2/docs",previous:{title:"Error handling",permalink:"/docs/4.2/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.2/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/13b4aeb1.62d51a95.js b/assets/js/13b4aeb1.7a9401d1.js similarity index 98% rename from assets/js/13b4aeb1.62d51a95.js rename to assets/js/13b4aeb1.7a9401d1.js index 4ee0cc7b96..9ab2df1810 100644 --- a/assets/js/13b4aeb1.62d51a95.js +++ b/assets/js/13b4aeb1.7a9401d1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5521],{9787:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>l,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>r,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},s=void 0,r={unversionedId:"pagination",id:"version-3.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-3.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/3.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/pagination.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-3.0/docs",previous:{title:"File uploads",permalink:"/docs/3.0/file-uploads"},next:{title:"Custom output types",permalink:"/docs/3.0/custom-output-types"}},l={},p=[{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(d,(0,n.Z)({},u,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,i.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"In your query, simply return a class that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.kt)("p",null,'The "count" field returns the ',(0,i.kt)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5521],{9787:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>l,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>r,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},s=void 0,r={unversionedId:"pagination",id:"version-3.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-3.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/3.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/pagination.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-3.0/docs",previous:{title:"File uploads",permalink:"/docs/3.0/file-uploads"},next:{title:"Custom output types",permalink:"/docs/3.0/custom-output-types"}},l={},p=[{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(d,(0,n.Z)({},u,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,i.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"In your query, simply return a class that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.kt)("p",null,'The "count" field returns the ',(0,i.kt)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1428bdad.43320636.js b/assets/js/1428bdad.58de4f6f.js similarity index 99% rename from assets/js/1428bdad.43320636.js rename to assets/js/1428bdad.58de4f6f.js index 6bd201ed26..db994d8158 100644 --- a/assets/js/1428bdad.43320636.js +++ b/assets/js/1428bdad.58de4f6f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[635],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),i=a(7392),u=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,i]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,u.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=u.indexOf(t),n=i[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;t=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;t=u[a]??u[u.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},19:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>y,frontMatter:()=>p,metadata:()=>l,toc:()=>i});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const p={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,l={unversionedId:"custom-types",id:"version-6.1/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-6.1/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/custom-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom annotations",permalink:"/docs/field-middlewares"}},s={},i=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],u={toc:i},c="wrapper";function y(e){let{components:t,...a}=e;return(0,r.kt)(c,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[635],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),i=a(7392),u=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,i]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,u.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=u.indexOf(t),n=i[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;t=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;t=u[a]??u[u.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},19:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>y,frontMatter:()=>p,metadata:()=>l,toc:()=>i});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const p={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,l={unversionedId:"custom-types",id:"version-6.1/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-6.1/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/custom-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom annotations",permalink:"/docs/field-middlewares"}},s={},i=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],u={toc:i},c="wrapper";function y(e){let{components:t,...a}=e;return(0,r.kt)(c,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/143f7888.10d803c7.js b/assets/js/143f7888.252a04c0.js similarity index 99% rename from assets/js/143f7888.10d803c7.js rename to assets/js/143f7888.252a04c0.js index 2b2211adf4..a6470d87f2 100644 --- a/assets/js/143f7888.10d803c7.js +++ b/assets/js/143f7888.252a04c0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8702],{4973:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.1/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.1/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.1/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/migrating.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},sidebar:"version-4.1/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.1/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.1/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/annotations_reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8702],{4973:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.1/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.1/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.1/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/migrating.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},sidebar:"version-4.1/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.1/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.1/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/annotations_reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/16017aa6.3cc39c32.js b/assets/js/16017aa6.8d532e45.js similarity index 99% rename from assets/js/16017aa6.3cc39c32.js rename to assets/js/16017aa6.8d532e45.js index ad7a8276d5..43a3ced20b 100644 --- a/assets/js/16017aa6.3cc39c32.js +++ b/assets/js/16017aa6.8d532e45.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5207],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7194:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-4.3/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.3/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.3/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/input-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-4.3/docs",previous:{title:"External type declaration",permalink:"/docs/4.3/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5207],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7194:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-4.3/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.3/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.3/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/input-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-4.3/docs",previous:{title:"External type declaration",permalink:"/docs/4.3/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/16565e6a.521f71eb.js b/assets/js/16565e6a.8efa5fde.js similarity index 98% rename from assets/js/16565e6a.521f71eb.js rename to assets/js/16565e6a.8efa5fde.js index 69d3b41b42..bd4b75c29b 100644 --- a/assets/js/16565e6a.521f71eb.js +++ b/assets/js/16565e6a.8efa5fde.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8931],{6930:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-3.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/3.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/argument_resolving.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},u="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(u,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8931],{6930:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-3.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/3.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/argument_resolving.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},u="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(u,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/17518879.4da6c2ee.js b/assets/js/17518879.804a3db9.js similarity index 99% rename from assets/js/17518879.4da6c2ee.js rename to assets/js/17518879.804a3db9.js index 6987ca940f..de6440b2d3 100644 --- a/assets/js/17518879.4da6c2ee.js +++ b/assets/js/17518879.804a3db9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7040],{3872:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=t(7462),i=(t(7294),t(3905));t(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-4.3/changelog",title:"Changelog",description:"4.3.0",source:"@site/versioned_docs/version-4.3/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.3/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/CHANGELOG.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-4.3/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.3/semver"}},d={},p=[{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,i.kt)(u,(0,n.Z)({},s,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7040],{3872:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=t(7462),i=(t(7294),t(3905));t(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-4.3/changelog",title:"Changelog",description:"4.3.0",source:"@site/versioned_docs/version-4.3/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.3/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/CHANGELOG.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-4.3/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.3/semver"}},d={},p=[{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,i.kt)(u,(0,n.Z)({},s,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/18100524.d27c0f7e.js b/assets/js/18100524.38c63d00.js similarity index 99% rename from assets/js/18100524.d27c0f7e.js rename to assets/js/18100524.38c63d00.js index 87f36f4d9f..8b7f9f3308 100644 --- a/assets/js/18100524.d27c0f7e.js +++ b/assets/js/18100524.38c63d00.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3772],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),u=a(1980),s=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[u,s]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=u??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),h(e)}),[s,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(c(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},3720:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"version-3.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-3.0/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/3.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/custom_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3772],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),u=a(1980),s=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[u,s]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=u??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),h(e)}),[s,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(c(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},3720:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"version-3.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-3.0/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/3.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/custom_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1891fd2b.69638c22.js b/assets/js/1891fd2b.3626160c.js similarity index 99% rename from assets/js/1891fd2b.69638c22.js rename to assets/js/1891fd2b.3626160c.js index 078b221e05..04e2999244 100644 --- a/assets/js/1891fd2b.69638c22.js +++ b/assets/js/1891fd2b.3626160c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5904],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8544:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-5.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-5.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/5.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/custom-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-5.0/docs",previous:{title:"Pagination",permalink:"/docs/5.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5904],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8544:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-5.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-5.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/5.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/custom-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-5.0/docs",previous:{title:"Pagination",permalink:"/docs/5.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/18d6c9c9.c281afcc.js b/assets/js/18d6c9c9.ad2e854a.js similarity index 99% rename from assets/js/18d6c9c9.c281afcc.js rename to assets/js/18d6c9c9.ad2e854a.js index 4a3c81bf05..b445a57a88 100644 --- a/assets/js/18d6c9c9.c281afcc.js +++ b/assets/js/18d6c9c9.ad2e854a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[306],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(7294),a=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var r=n(7462),a=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:r,default:a}}=e;return{value:t,label:n,attributes:r,default:a}}))}function h(e){const{values:t,children:n}=e;return(0,a.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const r=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,a.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(r.location.search);t.set(s,e),r.replace({...r.location,search:t.toString()})}),[s,r])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:r}=e,s=h(e),[o,l]=(0,a.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=n.find((e=>e.default))??n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:r}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,s]=(0,c.Nk)(n);return[r,(0,a.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:r}),b=(()=>{const e=i??d;return p({value:e,tabValues:s})?e:null})();(0,a.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,a.useCallback)((e=>{if(!p({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),r=u[n].value;r!==l&&(d(t),i(r))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,s.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:r}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,a.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=f(e);return a.createElement("div",{className:(0,s.Z)("tabs-container",g.tabList)},a.createElement(v,(0,r.Z)({},e,t)),a.createElement(y,(0,r.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return a.createElement(k,(0,r.Z)({key:String(t)},e))}},3503:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>u});var r=n(7462),a=(n(7294),n(3905));n(1839),n(4866),n(5162);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},o=void 0,l={unversionedId:"prefetch-method",id:"version-6.1/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-6.1/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/prefetch-method.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/query-plan"},next:{title:"File uploads",permalink:"/docs/file-uploads"}},i={},u=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],c={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,a.kt)(d,(0,r.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"the-problem"},"The problem"),(0,a.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.kt)("p",null,"A naive implementation will do this:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,a.kt)("a",{parentName:"p",href:"/docs/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,a.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')),(0,a.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,a.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,a.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')),(0,a.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[306],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(7294),a=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var r=n(7462),a=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:r,default:a}}=e;return{value:t,label:n,attributes:r,default:a}}))}function h(e){const{values:t,children:n}=e;return(0,a.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const r=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,a.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(r.location.search);t.set(s,e),r.replace({...r.location,search:t.toString()})}),[s,r])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:r}=e,s=h(e),[o,l]=(0,a.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=n.find((e=>e.default))??n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:r}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,s]=(0,c.Nk)(n);return[r,(0,a.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:r}),b=(()=>{const e=i??d;return p({value:e,tabValues:s})?e:null})();(0,a.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,a.useCallback)((e=>{if(!p({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),r=u[n].value;r!==l&&(d(t),i(r))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,s.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:r}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,a.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=f(e);return a.createElement("div",{className:(0,s.Z)("tabs-container",g.tabList)},a.createElement(v,(0,r.Z)({},e,t)),a.createElement(y,(0,r.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return a.createElement(k,(0,r.Z)({key:String(t)},e))}},3503:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>u});var r=n(7462),a=(n(7294),n(3905));n(1839),n(4866),n(5162);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},o=void 0,l={unversionedId:"prefetch-method",id:"version-6.1/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-6.1/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/prefetch-method.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/query-plan"},next:{title:"File uploads",permalink:"/docs/file-uploads"}},i={},u=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],c={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,a.kt)(d,(0,r.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"the-problem"},"The problem"),(0,a.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.kt)("p",null,"A naive implementation will do this:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,a.kt)("a",{parentName:"p",href:"/docs/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,a.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')),(0,a.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,a.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,a.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.kt)("p",null,"For instance:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')),(0,a.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1a4e3797.1587bb31.js b/assets/js/1a4e3797.1587bb31.js new file mode 100644 index 0000000000..3f00cf9826 --- /dev/null +++ b/assets/js/1a4e3797.1587bb31.js @@ -0,0 +1,2 @@ +/*! For license information please see 1a4e3797.1587bb31.js.LICENSE.txt */ +(self.webpackChunk=self.webpackChunk||[]).push([[7920],{7331:e=>{function t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function n(e){return"object"==typeof e&&null!==e}function i(e){return void 0===e}e.exports=t,t.prototype._events=void 0,t.prototype._maxListeners=void 0,t.defaultMaxListeners=10,t.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},t.prototype.emit=function(e){var t,a,s,c,u,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||n(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var h=new Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}if(i(a=this._events[e]))return!1;if(r(a))switch(arguments.length){case 1:a.call(this);break;case 2:a.call(this,arguments[1]);break;case 3:a.call(this,arguments[1],arguments[2]);break;default:c=Array.prototype.slice.call(arguments,1),a.apply(this,c)}else if(n(a))for(c=Array.prototype.slice.call(arguments,1),s=(o=a.slice()).length,u=0;u0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){if(!r(t))throw TypeError("listener must be a function");var n=!1;function i(){this.removeListener(e,i),n||(n=!0,t.apply(this,arguments))}return i.listener=t,this.on(e,i),this},t.prototype.removeListener=function(e,t){var i,a,s,c;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(i=this._events[e]).length,a=-1,i===t||r(i.listener)&&i.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(n(i)){for(c=s;c-- >0;)if(i[c]===t||i[c].listener&&i[c].listener===t){a=c;break}if(a<0)return this;1===i.length?(i.length=0,delete this._events[e]):i.splice(a,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},t.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},t.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},t.listenerCount=function(e,t){return e.listenerCount(t)}},8131:(e,t,r)=>{"use strict";var n=r(9374),i=r(7775),a=r(3076);function s(e,t,r,i){return new n(e,t,r,i)}s.version=r(4336),s.AlgoliaSearchHelper=n,s.SearchParameters=i,s.SearchResults=a,e.exports=s},8078:(e,t,r)=>{"use strict";var n=r(7331);function i(e,t){this.main=e,this.fn=t,this.lastResults=null}r(4853)(i,n),i.prototype.detach=function(){this.removeAllListeners(),this.main.detachDerivedHelper(this)},i.prototype.getModifiedState=function(e){return this.fn(e)},e.exports=i},2437:(e,t,r)=>{"use strict";var n=r(2344),i=r(116),a=r(9803),s={addRefinement:function(e,t,r){if(s.isRefined(e,t,r))return e;var i=""+r,a=e[t]?e[t].concat(i):[i],c={};return c[t]=a,n({},c,e)},removeRefinement:function(e,t,r){if(void 0===r)return s.clearRefinement(e,(function(e,r){return t===r}));var n=""+r;return s.clearRefinement(e,(function(e,r){return t===r&&n===e}))},toggleRefinement:function(e,t,r){if(void 0===r)throw new Error("toggleRefinement should be used with a value");return s.isRefined(e,t,r)?s.removeRefinement(e,t,r):s.addRefinement(e,t,r)},clearRefinement:function(e,t,r){if(void 0===t)return i(e)?{}:e;if("string"==typeof t)return a(e,[t]);if("function"==typeof t){var n=!1,s=Object.keys(e).reduce((function(i,a){var s=e[a]||[],c=s.filter((function(e){return!t(e,a,r)}));return c.length!==s.length&&(n=!0),i[a]=c,i}),{});return n?s:e}},isRefined:function(e,t,r){var n=Boolean(e[t])&&e[t].length>0;if(void 0===r||!n)return n;var i=""+r;return-1!==e[t].indexOf(i)}};e.exports=s},7775:(e,t,r)=>{"use strict";var n=r(2344),i=r(7888),a=r(2686),s=r(185),c=r(116),u=r(9803),o=r(8023),h=r(6801),f=r(2437);function l(e,t){return Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((function(e,r){return l(t[r],e)})):e===t}function m(e){var t=e?m._parseNumbers(e):{};void 0===t.userToken||h(t.userToken)||console.warn("[algoliasearch-helper] The `userToken` parameter is invalid. This can lead to wrong analytics.\n - Format: [a-zA-Z0-9_-]{1,64}"),this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{};var r=this;Object.keys(t).forEach((function(e){var n=-1!==m.PARAMETERS.indexOf(e),i=void 0!==t[e];!n&&i&&(r[e]=t[e])}))}m.PARAMETERS=Object.keys(new m),m._parseNumbers=function(e){if(e instanceof m)return e;var t={};if(["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"].forEach((function(r){var n=e[r];if("string"==typeof n){var i=parseFloat(n);t[r]=isNaN(i)?n:i}})),Array.isArray(e.insideBoundingBox)&&(t.insideBoundingBox=e.insideBoundingBox.map((function(e){return Array.isArray(e)?e.map((function(e){return parseFloat(e)})):e}))),e.numericRefinements){var r={};Object.keys(e.numericRefinements).forEach((function(t){var n=e.numericRefinements[t]||{};r[t]={},Object.keys(n).forEach((function(e){var i=n[e].map((function(e){return Array.isArray(e)?e.map((function(e){return"string"==typeof e?parseFloat(e):e})):"string"==typeof e?parseFloat(e):e}));r[t][e]=i}))})),t.numericRefinements=r}return s(e,t)},m.make=function(e){var t=new m(e);return(e.hierarchicalFacets||[]).forEach((function(e){if(e.rootPath){var r=t.getHierarchicalRefinement(e.name);r.length>0&&0!==r[0].indexOf(e.rootPath)&&(t=t.clearRefinements(e.name)),0===(r=t.getHierarchicalRefinement(e.name)).length&&(t=t.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}})),t},m.validate=function(e,t){var r=t||{};return e.tagFilters&&r.tagRefinements&&r.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&r.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&r.numericRefinements&&c(r.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):c(e.numericRefinements)&&r.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},m.prototype={constructor:m,clearRefinements:function(e){var t={numericRefinements:this._clearNumericRefinements(e),facetsRefinements:f.clearRefinement(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:f.clearRefinement(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:f.clearRefinement(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:f.clearRefinement(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")};return t.numericRefinements===this.numericRefinements&&t.facetsRefinements===this.facetsRefinements&&t.facetsExcludes===this.facetsExcludes&&t.disjunctiveFacetsRefinements===this.disjunctiveFacetsRefinements&&t.hierarchicalFacetsRefinements===this.hierarchicalFacetsRefinements?this:this.setQueryParameters(t)},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e})},addNumericRefinement:function(e,t,r){var n=o(r);if(this.isNumericRefined(e,t,n))return this;var i=s({},this.numericRefinements);return i[e]=s({},i[e]),i[e][t]?(i[e][t]=i[e][t].slice(),i[e][t].push(n)):i[e][t]=[n],this.setQueryParameters({numericRefinements:i})},getConjunctiveRefinements:function(e){return this.isConjunctiveFacet(e)&&this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){return this.isDisjunctiveFacet(e)&&this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){return this.isConjunctiveFacet(e)&&this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,r){var n=r;return void 0!==n?this.isNumericRefined(e,t,n)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(r,i){return i===e&&r.op===t&&l(r.val,o(n))}))}):this:void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(r,n){return n===e&&r.op===t}))}):this:this.isNumericRefined(e)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(t,r){return r===e}))}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){if(void 0===e)return c(this.numericRefinements)?{}:this.numericRefinements;if("string"==typeof e)return u(this.numericRefinements,[e]);if("function"==typeof e){var t=!1,r=this.numericRefinements,n=Object.keys(r).reduce((function(n,i){var a=r[i],s={};return a=a||{},Object.keys(a).forEach((function(r){var n=a[r]||[],c=[];n.forEach((function(t){e({val:t,op:r},i,"numeric")||c.push(t)})),c.length!==n.length&&(t=!0),s[r]=c})),n[i]=s,n}),{});return t?n:this.numericRefinements}},addFacet:function(e){return this.isConjunctiveFacet(e)?this:this.setQueryParameters({facets:this.facets.concat([e])})},addDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this:this.setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.concat([e])})},addHierarchicalFacet:function(e){if(this.isHierarchicalFacet(e.name))throw new Error("Cannot declare two hierarchical facets with the same name: `"+e.name+"`");return this.setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.concat([e])})},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({facetsRefinements:f.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({facetsExcludes:f.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return f.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({disjunctiveFacetsRefinements:f.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacet:function(e){return this.isConjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({facets:this.facets.filter((function(t){return t!==e}))}):this},removeDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.filter((function(t){return t!==e}))}):this},removeHierarchicalFacet:function(e){return this.isHierarchicalFacet(e)?this.clearRefinements(e).setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.filter((function(t){return t.name!==e}))}):this},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({facetsRefinements:f.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({facetsExcludes:f.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return f.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({disjunctiveFacetsRefinements:f.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.filter((function(t){return t!==e}))};return this.setQueryParameters(t)},toggleRefinement:function(e,t){return this.toggleFacetRefinement(e,t)},toggleFacetRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleConjunctiveFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleConjunctiveFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsRefinements:f.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsExcludes:f.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({disjunctiveFacetsRefinements:f.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),i={};return void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+r))?-1===t.indexOf(r)?i[e]=[]:i[e]=[t.slice(0,t.lastIndexOf(r))]:i[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:n({},i,this.hierarchicalFacetsRefinements)})},addHierarchicalFacetRefinement:function(e,t){if(this.isHierarchicalFacetRefined(e))throw new Error(e+" is already refined.");if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration.");var r={};return r[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:n({},r,this.hierarchicalFacetsRefinements)})},removeHierarchicalFacetRefinement:function(e){if(!this.isHierarchicalFacetRefined(e))return this;var t={};return t[e]=[],this.setQueryParameters({hierarchicalFacetsRefinements:n({},t,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return this.disjunctiveFacets.indexOf(e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return this.facets.indexOf(e)>-1},isFacetRefined:function(e,t){return!!this.isConjunctiveFacet(e)&&f.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){return!!this.isConjunctiveFacet(e)&&f.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){return!!this.isDisjunctiveFacet(e)&&f.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))return!1;var r=this.getHierarchicalRefinement(e);return t?-1!==r.indexOf(t):r.length>0},isNumericRefined:function(e,t,r){if(void 0===r&&void 0===t)return Boolean(this.numericRefinements[e]);var n=this.numericRefinements[e]&&void 0!==this.numericRefinements[e][t];if(void 0===r||!n)return n;var a,s,c=o(r),u=void 0!==(a=this.numericRefinements[e][t],s=c,i(a,(function(e){return l(e,s)})));return n&&u},isTagRefined:function(e){return-1!==this.tagRefinements.indexOf(e)},getRefinedDisjunctiveFacets:function(){var e=this,t=a(Object.keys(this.numericRefinements).filter((function(t){return Object.keys(e.numericRefinements[t]).length>0})),this.disjunctiveFacets);return Object.keys(this.disjunctiveFacetsRefinements).filter((function(t){return e.disjunctiveFacetsRefinements[t].length>0})).concat(t).concat(this.getRefinedHierarchicalFacets()).sort()},getRefinedHierarchicalFacets:function(){var e=this;return a(this.hierarchicalFacets.map((function(e){return e.name})),Object.keys(this.hierarchicalFacetsRefinements).filter((function(t){return e.hierarchicalFacetsRefinements[t].length>0}))).sort()},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return this.disjunctiveFacets.filter((function(t){return-1===e.indexOf(t)}))},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","hierarchicalFacets","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={},r=this;return Object.keys(this).forEach((function(n){var i=r[n];-1===e.indexOf(n)&&void 0!==i&&(t[n]=i)})),t},setQueryParameter:function(e,t){if(this[e]===t)return this;var r={};return r[e]=t,this.setQueryParameters(r)},setQueryParameters:function(e){if(!e)return this;var t=m.validate(this,e);if(t)throw t;var r=this,n=m._parseNumbers(e),i=Object.keys(this).reduce((function(e,t){return e[t]=r[t],e}),{}),a=Object.keys(n).reduce((function(e,t){var r=void 0!==e[t],i=void 0!==n[t];return r&&!i?u(e,[t]):(i&&(e[t]=n[t]),e)}),i);return new this.constructor(a)},resetPage:function(){return void 0===this.page?this:this.setPage(0)},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"!=typeof e.showParentLevel||e.showParentLevel},getHierarchicalFacetByName:function(e){return i(this.hierarchicalFacets,(function(t){return t.name===e}))},getHierarchicalFacetBreadcrumb:function(e){if(!this.isHierarchicalFacet(e))return[];var t=this.getHierarchicalRefinement(e)[0];if(!t)return[];var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e));return t.split(r).map((function(e){return e.trim()}))},toString:function(){return JSON.stringify(this,null,2)}},e.exports=m},210:(e,t,r)=>{"use strict";e.exports=function(e){return function(t,r){var n=e.hierarchicalFacets[r],o=e.hierarchicalFacetsRefinements[n.name]&&e.hierarchicalFacetsRefinements[n.name][0]||"",h=e._getHierarchicalFacetSeparator(n),f=e._getHierarchicalRootPath(n),l=e._getHierarchicalShowParentLevel(n),m=a(e._getHierarchicalFacetSortBy(n)),d=t.every((function(e){return e.exhaustive})),p=function(e,t,r,n,a){return function(o,h,f){var l=o;if(f>0){var m=0;for(l=o;m{"use strict";var n=r(4587),i=r(2344),a=r(4039),s=r(7888),c=r(9725),u=r(2293),o=r(185),h=r(2148),f=a.escapeFacetValue,l=a.unescapeFacetValue,m=r(210);function d(e){var t={};return e.forEach((function(e,r){t[e]=r})),t}function p(e,t,r){t&&t[r]&&(e.stats=t[r])}function v(e,t,r){var a=t[0];this._rawResults=t;var u=this;Object.keys(a).forEach((function(e){u[e]=a[e]}));var h=o({persistHierarchicalRootCount:!1},r);Object.keys(h).forEach((function(e){u[e]=h[e]})),this.processingTimeMS=t.reduce((function(e,t){return void 0===t.processingTimeMS?e:e+t.processingTimeMS}),0),this.disjunctiveFacets=[],this.hierarchicalFacets=e.hierarchicalFacets.map((function(){return[]})),this.facets=[];var f=e.getRefinedDisjunctiveFacets(),v=d(e.facets),g=d(e.disjunctiveFacets),y=1,R=a.facets||{};Object.keys(R).forEach((function(t){var r,n,i=R[t],o=(r=e.hierarchicalFacets,n=t,s(r,(function(e){return(e.attributes||[]).indexOf(n)>-1})));if(o){var h=o.attributes.indexOf(t),f=c(e.hierarchicalFacets,(function(e){return e.name===o.name}));u.hierarchicalFacets[f][h]={attribute:t,data:i,exhaustive:a.exhaustiveFacetsCount}}else{var l,m=-1!==e.disjunctiveFacets.indexOf(t),d=-1!==e.facets.indexOf(t);m&&(l=g[t],u.disjunctiveFacets[l]={name:t,data:i,exhaustive:a.exhaustiveFacetsCount},p(u.disjunctiveFacets[l],a.facets_stats,t)),d&&(l=v[t],u.facets[l]={name:t,data:i,exhaustive:a.exhaustiveFacetsCount},p(u.facets[l],a.facets_stats,t))}})),this.hierarchicalFacets=n(this.hierarchicalFacets),f.forEach((function(r){var n=t[y],s=n&&n.facets?n.facets:{},h=e.getHierarchicalFacetByName(r);Object.keys(s).forEach((function(t){var r,f=s[t];if(h){r=c(e.hierarchicalFacets,(function(e){return e.name===h.name}));var m=c(u.hierarchicalFacets[r],(function(e){return e.attribute===t}));if(-1===m)return;u.hierarchicalFacets[r][m].data=o({},u.hierarchicalFacets[r][m].data,f)}else{r=g[t];var d=a.facets&&a.facets[t]||{};u.disjunctiveFacets[r]={name:t,data:i({},f,d),exhaustive:n.exhaustiveFacetsCount},p(u.disjunctiveFacets[r],n.facets_stats,t),e.disjunctiveFacetsRefinements[t]&&e.disjunctiveFacetsRefinements[t].forEach((function(n){!u.disjunctiveFacets[r].data[n]&&e.disjunctiveFacetsRefinements[t].indexOf(l(n))>-1&&(u.disjunctiveFacets[r].data[n]=0)}))}})),y++})),e.getRefinedHierarchicalFacets().forEach((function(r){var n=e.getHierarchicalFacetByName(r),a=e._getHierarchicalFacetSeparator(n),s=e.getHierarchicalRefinement(r);0===s.length||s[0].split(a).length<2||t.slice(y).forEach((function(t){var r=t&&t.facets?t.facets:{};Object.keys(r).forEach((function(t){var o=r[t],h=c(e.hierarchicalFacets,(function(e){return e.name===n.name})),f=c(u.hierarchicalFacets[h],(function(e){return e.attribute===t}));if(-1!==f){var l={};if(s.length>0&&!u.persistHierarchicalRootCount){var m=s[0].split(a)[0];l[m]=u.hierarchicalFacets[h][f].data[m]}u.hierarchicalFacets[h][f].data=i(l,o,u.hierarchicalFacets[h][f].data)}})),y++}))})),Object.keys(e.facetsExcludes).forEach((function(t){var r=e.facetsExcludes[t],n=v[t];u.facets[n]={name:t,data:R[t],exhaustive:a.exhaustiveFacetsCount},r.forEach((function(e){u.facets[n]=u.facets[n]||{name:t},u.facets[n].data=u.facets[n].data||{},u.facets[n].data[e]=0}))})),this.hierarchicalFacets=this.hierarchicalFacets.map(m(e)),this.facets=n(this.facets),this.disjunctiveFacets=n(this.disjunctiveFacets),this._state=e}function g(e,t){function r(e){return e.name===t}if(e._state.isConjunctiveFacet(t)){var n=s(e.facets,r);return n?Object.keys(n.data).map((function(r){var i=f(r);return{name:r,escapedValue:i,count:n.data[r],isRefined:e._state.isFacetRefined(t,i),isExcluded:e._state.isExcludeRefined(t,r)}})):[]}if(e._state.isDisjunctiveFacet(t)){var i=s(e.disjunctiveFacets,r);return i?Object.keys(i.data).map((function(r){var n=f(r);return{name:r,escapedValue:n,count:i.data[r],isRefined:e._state.isDisjunctiveFacetRefined(t,n)}})):[]}if(e._state.isHierarchicalFacet(t)){var a=s(e.hierarchicalFacets,r);if(!a)return a;var c=e._state.getHierarchicalFacetByName(t),u=e._state._getHierarchicalFacetSeparator(c),o=l(e._state.getHierarchicalRefinement(t)[0]||"");0===o.indexOf(c.rootPath)&&(o=o.replace(c.rootPath+u,""));var h=o.split(u);return h.unshift(t),y(a,h,0),a}}function y(e,t,r){e.isRefined=e.name===t[r],e.data&&e.data.forEach((function(e){y(e,t,r+1)}))}function R(e,t,r,n){if(n=n||0,Array.isArray(t))return e(t,r[n]);if(!t.data||0===t.data.length)return t;var a=t.data.map((function(t){return R(e,t,r,n+1)})),s=e(a,r[n]);return i({data:s},t)}function F(e,t){var r=s(e,(function(e){return e.name===t}));return r&&r.stats}function b(e,t,r,n,i){var a=s(i,(function(e){return e.name===r})),c=a&&a.data&&a.data[n]?a.data[n]:0,u=a&&a.exhaustive||!1;return{type:t,attributeName:r,name:n,count:c,exhaustive:u}}v.prototype.getFacetByName=function(e){function t(t){return t.name===e}return s(this.facets,t)||s(this.disjunctiveFacets,t)||s(this.hierarchicalFacets,t)},v.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],v.prototype.getFacetValues=function(e,t){var r=g(this,e);if(r){var n,a=i({},t,{sortBy:v.DEFAULT_SORT,facetOrdering:!(t&&t.sortBy)}),s=this;if(Array.isArray(r))n=[e];else n=s._state.getHierarchicalFacetByName(r.name).attributes;return R((function(e,t){if(a.facetOrdering){var r=function(e,t){return e.renderingContent&&e.renderingContent.facetOrdering&&e.renderingContent.facetOrdering.values&&e.renderingContent.facetOrdering.values[t]}(s,t);if(r)return function(e,t){var r=[],n=[],i=(t.order||[]).reduce((function(e,t,r){return e[t]=r,e}),{});e.forEach((function(e){var t=e.path||e.name;void 0!==i[t]?r[i[t]]=e:n.push(e)})),r=r.filter((function(e){return e}));var a,s=t.sortRemainingBy;return"hidden"===s?r:(a="alpha"===s?[["path","name"],["asc","asc"]]:[["count"],["desc"]],r.concat(h(n,a[0],a[1])))}(e,r)}if(Array.isArray(a.sortBy)){var n=u(a.sortBy,v.DEFAULT_SORT);return h(e,n[0],n[1])}if("function"==typeof a.sortBy)return function(e,t){return t.sort(e)}(a.sortBy,e);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")}),r,n)}},v.prototype.getFacetStats=function(e){return this._state.isConjunctiveFacet(e)?F(this.facets,e):this._state.isDisjunctiveFacet(e)?F(this.disjunctiveFacets,e):void 0},v.prototype.getRefinements=function(){var e=this._state,t=this,r=[];return Object.keys(e.facetsRefinements).forEach((function(n){e.facetsRefinements[n].forEach((function(i){r.push(b(e,"facet",n,i,t.facets))}))})),Object.keys(e.facetsExcludes).forEach((function(n){e.facetsExcludes[n].forEach((function(i){r.push(b(e,"exclude",n,i,t.facets))}))})),Object.keys(e.disjunctiveFacetsRefinements).forEach((function(n){e.disjunctiveFacetsRefinements[n].forEach((function(i){r.push(b(e,"disjunctive",n,i,t.disjunctiveFacets))}))})),Object.keys(e.hierarchicalFacetsRefinements).forEach((function(n){e.hierarchicalFacetsRefinements[n].forEach((function(i){r.push(function(e,t,r,n){var i=e.getHierarchicalFacetByName(t),a=e._getHierarchicalFacetSeparator(i),c=r.split(a),u=s(n,(function(e){return e.name===t})),o=c.reduce((function(e,t){var r=e&&s(e.data,(function(e){return e.name===t}));return void 0!==r?r:e}),u),h=o&&o.count||0,f=o&&o.exhaustive||!1,l=o&&o.path||"";return{type:"hierarchical",attributeName:t,name:l,count:h,exhaustive:f}}(e,n,i,t.hierarchicalFacets))}))})),Object.keys(e.numericRefinements).forEach((function(t){var n=e.numericRefinements[t];Object.keys(n).forEach((function(e){n[e].forEach((function(n){r.push({type:"numeric",attributeName:t,name:n,numericValue:n,operator:e})}))}))})),e.tagRefinements.forEach((function(e){r.push({type:"tag",attributeName:"_tags",name:e})})),r},e.exports=v},9374:(e,t,r)=>{"use strict";var n=r(7331),i=r(8078),a=r(4039).escapeFacetValue,s=r(4853),c=r(185),u=r(116),o=r(9803),h=r(6394),f=r(7775),l=r(3076),m=r(4336);function d(e,t,r,n){"function"==typeof e.addAlgoliaAgent&&e.addAlgoliaAgent("JS Helper ("+m+")"),this.setClient(e);var i=r||{};i.index=t,this.state=f.make(i),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1,this.derivedHelpers=[],this._currentNbQueries=0,this._searchResultsOptions=n}function p(e){if(e<0)throw new Error("Page requested below 0.");return this._change({state:this.state.setPage(e),isPageReset:!1}),this}function v(){return this.state.page}s(d,n),d.prototype.search=function(){return this._search({onlyWithDerivedHelpers:!1}),this},d.prototype.searchOnlyWithDerivedHelpers=function(){return this._search({onlyWithDerivedHelpers:!0}),this},d.prototype.getQuery=function(){var e=this.state;return h._getHitsSearchParams(e)},d.prototype.searchOnce=function(e,t){var r=e?this.state.setQueryParameters(e):this.state,n=h._getQueries(r.index,r),i=this;if(this._currentNbQueries++,this.emit("searchOnce",{state:r}),!t)return this.client.search(n).then((function(e){return i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),{content:new l(r,e.results),state:r,_originalResponse:e}}),(function(e){throw i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),e}));this.client.search(n).then((function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(null,new l(r,e.results),r)})).catch((function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(e,null,r)}))},d.prototype.findAnswers=function(e){console.warn("[algoliasearch-helper] answers is no longer supported");var t=this.state,r=this.derivedHelpers[0];if(!r)return Promise.resolve([]);var n=r.getModifiedState(t),i=c({attributesForPrediction:e.attributesForPrediction,nbHits:e.nbHits},{params:o(h._getHitsSearchParams(n),["attributesToSnippet","hitsPerPage","restrictSearchableAttributes","snippetEllipsisText"])}),a="search for answers was called, but this client does not have a function client.initIndex(index).findAnswers";if("function"!=typeof this.client.initIndex)throw new Error(a);var s=this.client.initIndex(n.index);if("function"!=typeof s.findAnswers)throw new Error(a);return s.findAnswers(n.query,e.queryLanguages,i)},d.prototype.searchForFacetValues=function(e,t,r,n){var i="function"==typeof this.client.searchForFacetValues,s="function"==typeof this.client.initIndex;if(!i&&!s&&"function"!=typeof this.client.search)throw new Error("search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues");var c=this.state.setQueryParameters(n||{}),u=c.isDisjunctiveFacet(e),o=h.getSearchForFacetQuery(e,t,r,c);this._currentNbQueries++;var f,l=this;return i?f=this.client.searchForFacetValues([{indexName:c.index,params:o}]):s?f=this.client.initIndex(c.index).searchForFacetValues(o):(delete o.facetName,f=this.client.search([{type:"facet",facet:e,indexName:c.index,params:o}]).then((function(e){return e.results[0]}))),this.emit("searchForFacetValues",{state:c,facet:e,query:t}),f.then((function(t){return l._currentNbQueries--,0===l._currentNbQueries&&l.emit("searchQueueEmpty"),(t=Array.isArray(t)?t[0]:t).facetHits.forEach((function(t){t.escapedValue=a(t.value),t.isRefined=u?c.isDisjunctiveFacetRefined(e,t.escapedValue):c.isFacetRefined(e,t.escapedValue)})),t}),(function(e){throw l._currentNbQueries--,0===l._currentNbQueries&&l.emit("searchQueueEmpty"),e}))},d.prototype.setQuery=function(e){return this._change({state:this.state.resetPage().setQuery(e),isPageReset:!0}),this},d.prototype.clearRefinements=function(e){return this._change({state:this.state.resetPage().clearRefinements(e),isPageReset:!0}),this},d.prototype.clearTags=function(){return this._change({state:this.state.resetPage().clearTags(),isPageReset:!0}),this},d.prototype.addDisjunctiveFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addDisjunctiveFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},d.prototype.addHierarchicalFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addHierarchicalFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addNumericRefinement=function(e,t,r){return this._change({state:this.state.resetPage().addNumericRefinement(e,t,r),isPageReset:!0}),this},d.prototype.addFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},d.prototype.addFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().addExcludeRefinement(e,t),isPageReset:!0}),this},d.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},d.prototype.addTag=function(e){return this._change({state:this.state.resetPage().addTagRefinement(e),isPageReset:!0}),this},d.prototype.removeNumericRefinement=function(e,t,r){return this._change({state:this.state.resetPage().removeNumericRefinement(e,t,r),isPageReset:!0}),this},d.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().removeDisjunctiveFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},d.prototype.removeHierarchicalFacetRefinement=function(e){return this._change({state:this.state.resetPage().removeHierarchicalFacetRefinement(e),isPageReset:!0}),this},d.prototype.removeFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().removeFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},d.prototype.removeFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().removeExcludeRefinement(e,t),isPageReset:!0}),this},d.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},d.prototype.removeTag=function(e){return this._change({state:this.state.resetPage().removeTagRefinement(e),isPageReset:!0}),this},d.prototype.toggleFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().toggleExcludeFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},d.prototype.toggleRefinement=function(e,t){return this.toggleFacetRefinement(e,t)},d.prototype.toggleFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().toggleFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.toggleRefine=function(){return this.toggleFacetRefinement.apply(this,arguments)},d.prototype.toggleTag=function(e){return this._change({state:this.state.resetPage().toggleTagRefinement(e),isPageReset:!0}),this},d.prototype.nextPage=function(){var e=this.state.page||0;return this.setPage(e+1)},d.prototype.previousPage=function(){var e=this.state.page||0;return this.setPage(e-1)},d.prototype.setCurrentPage=p,d.prototype.setPage=p,d.prototype.setIndex=function(e){return this._change({state:this.state.resetPage().setIndex(e),isPageReset:!0}),this},d.prototype.setQueryParameter=function(e,t){return this._change({state:this.state.resetPage().setQueryParameter(e,t),isPageReset:!0}),this},d.prototype.setState=function(e){return this._change({state:f.make(e),isPageReset:!1}),this},d.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new f(e),this},d.prototype.hasRefinements=function(e){return!!u(this.state.getNumericRefinements(e))||(this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):!!this.state.isHierarchicalFacet(e)&&this.state.isHierarchicalFacetRefined(e))},d.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},d.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},d.prototype.hasTag=function(e){return this.state.isTagRefined(e)},d.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},d.prototype.getIndex=function(){return this.state.index},d.prototype.getCurrentPage=v,d.prototype.getPage=v,d.prototype.getTags=function(){return this.state.tagRefinements},d.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e))this.state.getConjunctiveRefinements(e).forEach((function(e){t.push({value:e,type:"conjunctive"})})),this.state.getExcludeRefinements(e).forEach((function(e){t.push({value:e,type:"exclude"})}));else if(this.state.isDisjunctiveFacet(e)){this.state.getDisjunctiveRefinements(e).forEach((function(e){t.push({value:e,type:"disjunctive"})}))}var r=this.state.getNumericRefinements(e);return Object.keys(r).forEach((function(e){var n=r[e];t.push({value:n,operator:e,type:"numeric"})})),t},d.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},d.prototype.getHierarchicalFacetBreadcrumb=function(e){return this.state.getHierarchicalFacetBreadcrumb(e)},d.prototype._search=function(e){var t=this.state,r=[],n=[];e.onlyWithDerivedHelpers||(n=h._getQueries(t.index,t),r.push({state:t,queriesCount:n.length,helper:this}),this.emit("search",{state:t,results:this.lastResults}));var i=this.derivedHelpers.map((function(e){var n=e.getModifiedState(t),i=n.index?h._getQueries(n.index,n):[];return r.push({state:n,queriesCount:i.length,helper:e}),e.emit("search",{state:n,results:e.lastResults}),i})),a=Array.prototype.concat.apply(n,i),s=this._queryId++;if(this._currentNbQueries++,!a.length)return Promise.resolve({results:[]}).then(this._dispatchAlgoliaResponse.bind(this,r,s));try{this.client.search(a).then(this._dispatchAlgoliaResponse.bind(this,r,s)).catch(this._dispatchAlgoliaError.bind(this,s))}catch(c){this.emit("error",{error:c})}},d.prototype._dispatchAlgoliaResponse=function(e,t,r){var n=this;if(!(t0},d.prototype._change=function(e){var t=e.state,r=e.isPageReset;t!==this.state&&(this.state=t,this.emit("change",{state:this.state,results:this.lastResults,isPageReset:r}))},d.prototype.clearCache=function(){return this.client.clearCache&&this.client.clearCache(),this},d.prototype.setClient=function(e){return this.client===e||("function"==typeof e.addAlgoliaAgent&&e.addAlgoliaAgent("JS Helper ("+m+")"),this.client=e),this},d.prototype.getClient=function(){return this.client},d.prototype.derive=function(e){var t=new i(this,e);return this.derivedHelpers.push(t),t},d.prototype.detachDerivedHelper=function(e){var t=this.derivedHelpers.indexOf(e);if(-1===t)throw new Error("Derived helper already detached");this.derivedHelpers.splice(t,1)},d.prototype.hasPendingRequests=function(){return this._currentNbQueries>0},e.exports=d},4587:e=>{"use strict";e.exports=function(e){return Array.isArray(e)?e.filter(Boolean):[]}},2344:e=>{"use strict";e.exports=function(){return Array.prototype.slice.call(arguments).reduceRight((function(e,t){return Object.keys(Object(t)).forEach((function(r){void 0!==t[r]&&(void 0!==e[r]&&delete e[r],e[r]=t[r])})),e}),{})}},4039:e=>{"use strict";e.exports={escapeFacetValue:function(e){return"string"!=typeof e?e:String(e).replace(/^-/,"\\-")},unescapeFacetValue:function(e){return"string"!=typeof e?e:e.replace(/^\\-/,"-")}}},7888:e=>{"use strict";e.exports=function(e,t){if(Array.isArray(e))for(var r=0;r{"use strict";e.exports=function(e,t){if(!Array.isArray(e))return-1;for(var r=0;r{"use strict";var n=r(7888);e.exports=function(e,t){var r=(t||[]).map((function(e){return e.split(":")}));return e.reduce((function(e,t){var i=t.split(":"),a=n(r,(function(e){return e[0]===i[0]}));return i.length>1||!a?(e[0].push(i[0]),e[1].push(i[1]),e):(e[0].push(a[0]),e[1].push(a[1]),e)}),[[],[]])}},4853:e=>{"use strict";e.exports=function(e,t){e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},2686:e=>{"use strict";e.exports=function(e,t){return e.filter((function(r,n){return t.indexOf(r)>-1&&e.indexOf(r)===n}))}},185:e=>{"use strict";function t(e){return"function"==typeof e||Array.isArray(e)||"[object Object]"===Object.prototype.toString.call(e)}function r(e,n){if(e===n)return e;for(var i in n)if(Object.prototype.hasOwnProperty.call(n,i)&&"__proto__"!==i&&"constructor"!==i){var a=n[i],s=e[i];void 0!==s&&void 0===a||(t(s)&&t(a)?e[i]=r(s,a):e[i]="object"==typeof(c=a)&&null!==c?r(Array.isArray(c)?[]:{},c):c)}var c;return e}e.exports=function(e){t(e)||(e={});for(var n=1,i=arguments.length;n{"use strict";e.exports=function(e){return e&&Object.keys(e).length>0}},9803:e=>{"use strict";e.exports=function(e,t){if(null===e)return{};var r,n,i={},a=Object.keys(e);for(n=0;n=0||(i[r]=e[r]);return i}},2148:e=>{"use strict";function t(e,t){if(e!==t){var r=void 0!==e,n=null===e,i=void 0!==t,a=null===t;if(!a&&e>t||n&&i||!r)return 1;if(!n&&e=n.length?a:"desc"===n[i]?-a:a}return e.index-r.index})),i.map((function(e){return e.value}))}},8023:e=>{"use strict";e.exports=function e(t){if("number"==typeof t)return t;if("string"==typeof t)return parseFloat(t);if(Array.isArray(t))return t.map(e);throw new Error("The value should be a number, a parsable string or an array of those.")}},6394:(e,t,r)=>{"use strict";var n=r(185);function i(e){return Object.keys(e).sort().reduce((function(t,r){return t[r]=e[r],t}),{})}var a={_getQueries:function(e,t){var r=[];return r.push({indexName:e,params:a._getHitsSearchParams(t)}),t.getRefinedDisjunctiveFacets().forEach((function(n){r.push({indexName:e,params:a._getDisjunctiveFacetSearchParams(t,n)})})),t.getRefinedHierarchicalFacets().forEach((function(n){var i=t.getHierarchicalFacetByName(n),s=t.getHierarchicalRefinement(n),c=t._getHierarchicalFacetSeparator(i);if(s.length>0&&s[0].split(c).length>1){var u=s[0].split(c).slice(0,-1).reduce((function(e,t,r){return e.concat({attribute:i.attributes[r],value:0===r?t:[e[e.length-1].value,t].join(c)})}),[]);u.forEach((function(n,s){var c=a._getDisjunctiveFacetSearchParams(t,n.attribute,0===s);function o(e){return i.attributes.some((function(t){return t===e.split(":")[0]}))}var h=(c.facetFilters||[]).reduce((function(e,t){if(Array.isArray(t)){var r=t.filter((function(e){return!o(e)}));r.length>0&&e.push(r)}return"string"!=typeof t||o(t)||e.push(t),e}),[]),f=u[s-1];c.facetFilters=s>0?h.concat(f.attribute+":"+f.value):h.length>0?h:void 0,r.push({indexName:e,params:c})}))}})),r},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(a._getHitsHierarchicalFacetsAttributes(e)).sort(),r=a._getFacetFilters(e),s=a._getNumericFilters(e),c=a._getTagFilters(e),u={facets:t.indexOf("*")>-1?["*"]:t,tagFilters:c};return r.length>0&&(u.facetFilters=r),s.length>0&&(u.numericFilters=s),i(n({},e.getQueryParams(),u))},_getDisjunctiveFacetSearchParams:function(e,t,r){var s=a._getFacetFilters(e,t,r),c=a._getNumericFilters(e,t),u=a._getTagFilters(e),o={hitsPerPage:0,page:0,analytics:!1,clickAnalytics:!1};u.length>0&&(o.tagFilters=u);var h=e.getHierarchicalFacetByName(t);return o.facets=h?a._getDisjunctiveHierarchicalFacetAttribute(e,h,r):t,c.length>0&&(o.numericFilters=c),s.length>0&&(o.facetFilters=s),i(n({},e.getQueryParams(),o))},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var r=[];return Object.keys(e.numericRefinements).forEach((function(n){var i=e.numericRefinements[n]||{};Object.keys(i).forEach((function(e){var a=i[e]||[];t!==n&&a.forEach((function(t){if(Array.isArray(t)){var i=t.map((function(t){return n+e+t}));r.push(i)}else r.push(n+e+t)}))}))})),r},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,r){var n=[],i=e.facetsRefinements||{};Object.keys(i).sort().forEach((function(e){(i[e]||[]).slice().sort().forEach((function(t){n.push(e+":"+t)}))}));var a=e.facetsExcludes||{};Object.keys(a).sort().forEach((function(e){(a[e]||[]).sort().forEach((function(t){n.push(e+":-"+t)}))}));var s=e.disjunctiveFacetsRefinements||{};Object.keys(s).sort().forEach((function(e){var r=s[e]||[];if(e!==t&&r&&0!==r.length){var i=[];r.slice().sort().forEach((function(t){i.push(e+":"+t)})),n.push(i)}}));var c=e.hierarchicalFacetsRefinements||{};return Object.keys(c).sort().forEach((function(i){var a=(c[i]||[])[0];if(void 0!==a){var s,u,o=e.getHierarchicalFacetByName(i),h=e._getHierarchicalFacetSeparator(o),f=e._getHierarchicalRootPath(o);if(t===i){if(-1===a.indexOf(h)||!f&&!0===r||f&&f.split(h).length===a.split(h).length)return;f?(u=f.split(h).length-1,a=f):(u=a.split(h).length-2,a=a.slice(0,a.lastIndexOf(h))),s=o.attributes[u]}else u=a.split(h).length-1,s=o.attributes[u];s&&n.push([s+":"+a])}})),n},_getHitsHierarchicalFacetsAttributes:function(e){return e.hierarchicalFacets.reduce((function(t,r){var n=e.getHierarchicalRefinement(r.name)[0];if(!n)return t.push(r.attributes[0]),t;var i=e._getHierarchicalFacetSeparator(r),a=n.split(i).length,s=r.attributes.slice(0,a+1);return t.concat(s)}),[])},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,r){var n=e._getHierarchicalFacetSeparator(t);if(!0===r){var i=e._getHierarchicalRootPath(t),a=0;return i&&(a=i.split(n).length),[t.attributes[a]]}var s=(e.getHierarchicalRefinement(t.name)[0]||"").split(n).length-1;return t.attributes.slice(0,s+1)},getSearchForFacetQuery:function(e,t,r,s){var c=s.isDisjunctiveFacet(e)?s.clearRefinements(e):s,u={facetQuery:t,facetName:e};return"number"==typeof r&&(u.maxFacetHits=r),i(n({},a._getHitsSearchParams(c),u))}};e.exports=a},6801:e=>{"use strict";e.exports=function(e){return null!==e&&/^[a-zA-Z0-9_-]{1,64}$/.test(e)}},4336:e=>{"use strict";e.exports="3.16.2"},290:function(e){e.exports=function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var r=[],n=!0,i=!1,a=void 0;try{for(var s,c=e[Symbol.iterator]();!(n=(s=c.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{n||null==c.return||c.return()}finally{if(i)throw a}}return r}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function a(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){c();var t=JSON.stringify(e);return a()[t]})).then((function(e){return Promise.all([e?e.value:t(),void 0!==e])})).then((function(e){var t=i(e,2),n=t[0],a=t[1];return Promise.all([n,a||r.miss(n)])})).then((function(e){return i(e,1)[0]}))},set:function(e,t){return Promise.resolve().then((function(){var i=a();return i[JSON.stringify(e)]={timestamp:(new Date).getTime(),value:t},n().setItem(r,JSON.stringify(i)),t}))},delete:function(e){return Promise.resolve().then((function(){var t=a();delete t[JSON.stringify(e)],n().setItem(r,JSON.stringify(t))}))},clear:function(){return Promise.resolve().then((function(){n().removeItem(r)}))}}}function c(e){var t=a(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return t().then((function(e){return Promise.all([e,r.miss(e)])})).then((function(e){return i(e,1)[0]}))},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,i).catch((function(){return c({caches:t}).get(e,n,i)}))},set:function(e,n){return r.set(e,n).catch((function(){return c({caches:t}).set(e,n)}))},delete:function(e){return r.delete(e).catch((function(){return c({caches:t}).delete(e)}))},clear:function(){return r.clear().catch((function(){return c({caches:t}).clear()}))}}}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var s=n(),c=i&&i.miss||function(){return Promise.resolve()};return s.then((function(e){return c(e)})).then((function(){return s}))},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function o(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}function h(e,t){return t?(Object.keys(t).forEach((function(r){e[r]=t[r](e)})),e):e}function f(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var d={Read:1,Write:2,Any:3},p=1,v=2,g=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function R(e){return"string"==typeof e?{protocol:"https",url:e,accept:d.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||d.Any}}var F="GET",b="POST";function P(e,t){return Promise.all(t.map((function(t){return e.get(t,(function(){return Promise.resolve(y(t))}))}))).then((function(e){var r=e.filter((function(e){return function(e){return e.status===p||Date.now()-e.lastUpdate>12e4}(e)})),n=e.filter((function(e){return function(e){return e.status===g&&Date.now()-e.lastUpdate<=12e4}(e)})),i=[].concat(a(r),a(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:i.length>0?i.map((function(e){return R(e)})):t}}))}function j(e,t,n,i){var s=[],c=function(e,t){if(e.method!==F&&(void 0!==e.data||void 0!==t.data)){var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}}(n,i),u=function(e,t){var n=r(r({},e.headers),t.headers),i={};return Object.keys(n).forEach((function(e){var t=n[e];i[e.toLowerCase()]=t})),i}(e,i),o=n.method,h=n.method!==F?{}:r(r({},n.data),i.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),h),i.queryParameters),l=0,m=function t(r,a){var h=r.pop();if(void 0===h)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:O(s)};var m={data:c,headers:u,method:o,url:E(h,n.path,f),connectTimeout:a(l,e.timeouts.connect),responseTimeout:a(l,i.timeout)},d=function(e){var t={request:m,response:e,host:h,triesLeft:r.length};return s.push(t),t},p={onSuccess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var i=d(n);return n.isTimedOut&&l++,Promise.all([e.logger.info("Retryable failure",w(i)),e.hostsCache.set(h,y(h,n.isTimedOut?g:v))]).then((function(){return t(r,a)}))},onFail:function(e){throw d(e),function(e,t){var r=e.content,n=e.status,i=r;try{i=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}(i,n,t)}(e,O(s))}};return e.requester.send(m).then((function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSuccess(e):t.onFail(e)}(e,p)}))};return P(e.hostsCache,t).then((function(e){return m(a(e.statelessHosts).reverse(),e.getTimeout)}))}function _(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function E(e,t,r){var n=x(r),i="".concat(e.protocol,"://").concat(e.url,"/").concat("/"===t.charAt(0)?t.substr(1):t);return n.length&&(i+="?".concat(n)),i}function x(e){return Object.keys(e).map((function(t){return f("%s=%s",t,(r=e[t],"[object Object]"===Object.prototype.toString.call(r)||"[object Array]"===Object.prototype.toString.call(r)?JSON.stringify(e[t]):e[t]));var r})).join("&")}function O(e){return e.map((function(e){return w(e)}))}function w(e){var t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},e),{},{request:r(r({},e.request),{},{headers:r(r({},e.request.headers),t)})})}var N=function(e){var t=e.appId,n=function(e,t,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers:function(){return e===l.WithinHeaders?n:{}},queryParameters:function(){return e===l.WithinQueryParameters?n:{}}}}(void 0!==e.authMode?e.authMode:l.WithinHeaders,t,e.apiKey),a=function(e){var t=e.hostsCache,r=e.logger,n=e.requester,a=e.requestsCache,s=e.responsesCache,c=e.timeouts,u=e.userAgent,o=e.hosts,h=e.queryParameters,f={hostsCache:t,logger:r,requester:n,requestsCache:a,responsesCache:s,timeouts:c,userAgent:u,headers:e.headers,queryParameters:h,hosts:o.map((function(e){return R(e)})),read:function(e,t){var r=m(t,f.timeouts.read),n=function(){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Read)})),e,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:e.cacheable))return n();var a={request:e,mappedRequestOptions:r,transporter:{queryParameters:f.queryParameters,headers:f.headers}};return f.responsesCache.get(a,(function(){return f.requestsCache.get(a,(function(){return f.requestsCache.set(a,n()).then((function(e){return Promise.all([f.requestsCache.delete(a),e])}),(function(e){return Promise.all([f.requestsCache.delete(a),Promise.reject(e)])})).then((function(e){var t=i(e,2);return t[0],t[1]}))}))}),{miss:function(e){return f.responsesCache.set(a,e)}})},write:function(e,t){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Write)})),e,m(t,f.timeouts.write))}};return f}(r(r({hosts:[{url:"".concat(t,"-dsn.algolia.net"),accept:d.Read},{url:"".concat(t,".algolia.net"),accept:d.Write}].concat(o([{url:"".concat(t,"-1.algolianet.com")},{url:"".concat(t,"-2.algolianet.com")},{url:"".concat(t,"-3.algolianet.com")}]))},e),{},{headers:r(r(r({},n.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:r(r({},n.queryParameters()),e.queryParameters)}));return h({transporter:a,appId:t,addAlgoliaAgent:function(e,t){a.userAgent.add({segment:e,version:t})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then((function(){}))}},e.methods)},A=function(e){return function(t,r){return t.method===F?e.transporter.read(t,r):e.transporter.write(t,r)}},H=function(e){return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return h({transporter:e.transporter,appId:e.appId,indexName:t},r.methods)}},S=function(e){return function(t,n){var i=t.map((function(e){return r(r({},e),{},{params:x(e.params||{})})}));return e.transporter.read({method:b,path:"1/indexes/*/queries",data:{requests:i},cacheable:!0},n)}},T=function(e){return function(t,i){return Promise.all(t.map((function(t){var a=t.params,s=a.facetName,c=a.facetQuery,u=n(a,["facetName","facetQuery"]);return H(e)(t.indexName,{methods:{searchForFacetValues:I}}).searchForFacetValues(s,c,r(r({},i),u))})))}},Q=function(e){return function(t,r,n){return e.transporter.read({method:b,path:f("1/answers/%s/prediction",e.indexName),data:{query:t,queryLanguages:r},cacheable:!0},n)}},C=function(e){return function(t,r){return e.transporter.read({method:b,path:f("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r)}},I=function(e){return function(t,r,n){return e.transporter.read({method:b,path:f("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},n)}},k=1,D=2,q=3;function V(e,t,n){var i,a={appId:e,apiKey:t,timeouts:{connect:1,read:2,write:30},requester:{send:function(e){return new Promise((function(t){var r=new XMLHttpRequest;r.open(e.method,e.url,!0),Object.keys(e.headers).forEach((function(t){return r.setRequestHeader(t,e.headers[t])}));var n,i=function(e,n){return setTimeout((function(){r.abort(),t({status:0,content:n,isTimedOut:!0})}),1e3*e)},a=i(e.connectTimeout,"Connection timeout");r.onreadystatechange=function(){r.readyState>r.OPENED&&void 0===n&&(clearTimeout(a),n=i(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)}))}},logger:(i=q,{debug:function(e,t){return k>=i&&console.debug(e,t),Promise.resolve()},info:function(e,t){return D>=i&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:u(),requestsCache:u({serializable:!1}),hostsCache:c({caches:[s({key:"".concat("4.22.1","-").concat(e)}),u()]}),userAgent:_("4.22.1").add({segment:"Browser",version:"lite"}),authMode:l.WithinQueryParameters};return N(r(r(r({},a),n),{},{methods:{search:S,searchForFacetValues:T,multipleQueries:S,multipleSearchForFacetValues:T,customRequest:A,initIndex:function(e){return function(t){return H(e)(t,{methods:{search:C,searchForFacetValues:I,findAnswers:Q}})}}}}))}return V.version="4.22.1",V}()},6675:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>A});var n=r(7294),i=r(6010),a=r(8131),s=r.n(a),c=r(290),u=r.n(c),o=r(412),h=r(5742),f=r(9960),l=r(143),m=r(2263);const d=["zero","one","two","few","many","other"];function p(e){return d.filter((t=>e.includes(t)))}const v={locale:"en",pluralForms:p(["one","other"]),select:e=>1===e?"one":"other"};function g(){const{i18n:{currentLocale:e}}=(0,m.Z)();return(0,n.useMemo)((()=>{try{return function(e){const t=new Intl.PluralRules(e);return{locale:e,pluralForms:p(t.resolvedOptions().pluralCategories),select:e=>t.select(e)}}(e)}catch(t){return console.error(`Failed to use Intl.PluralRules for locale "${e}".\nDocusaurus will fallback to the default (English) implementation.\nError: ${t.message}\n`),v}}),[e])}function y(){const e=g();return{selectMessage:(t,r)=>function(e,t,r){const n=e.split("|");if(1===n.length)return n[0];n.length>r.pluralForms.length&&console.error(`For locale=${r.locale}, a maximum of ${r.pluralForms.length} plural forms are expected (${r.pluralForms.join(",")}), but the message contains ${n.length}: ${e}`);const i=r.select(t),a=r.pluralForms.indexOf(i);return n[Math.min(a,n.length-1)]}(r,t,e)}}var R=r(6177),F=r(902),b=r(833),P=r(2128),j=r(5999),_=r(6278),E=r(239),x=r(7452);const O={searchQueryInput:"searchQueryInput_u2C7",searchVersionInput:"searchVersionInput_m0Ui",searchResultsColumn:"searchResultsColumn_JPFH",algoliaLogo:"algoliaLogo_rT1R",algoliaLogoPathFill:"algoliaLogoPathFill_WdUC",searchResultItem:"searchResultItem_Tv2o",searchResultItemHeading:"searchResultItemHeading_KbCB",searchResultItemPath:"searchResultItemPath_lhe1",searchResultItemSummary:"searchResultItemSummary_AEaO",searchQueryColumn:"searchQueryColumn_RTkw",searchVersionColumn:"searchVersionColumn_ypXd",searchLogoColumn:"searchLogoColumn_rJIA",loadingSpinner:"loadingSpinner_XVxU","loading-spin":"loading-spin_vzvp",loader:"loader_vvXV"};function w(e){let{docsSearchVersionsHelpers:t}=e;const r=Object.entries(t.allDocsData).filter((e=>{let[,t]=e;return t.versions.length>1}));return n.createElement("div",{className:(0,i.Z)("col","col--3","padding-left--none",O.searchVersionColumn)},r.map((e=>{let[i,a]=e;const s=r.length>1?`${i}: `:"";return n.createElement("select",{key:i,onChange:e=>t.setSearchVersion(i,e.target.value),defaultValue:t.searchVersions[i],className:O.searchVersionInput},a.versions.map(((e,t)=>n.createElement("option",{key:t,label:`${s}${e.label}`,value:e.name}))))})))}function N(){const{i18n:{currentLocale:e}}=(0,m.Z)(),{algolia:{appId:t,apiKey:r,indexName:a}}=(0,_.L)(),c=(0,E.l)(),d=function(){const{selectMessage:e}=y();return t=>e(t,(0,j.I)({id:"theme.SearchPage.documentsFound.plurals",description:'Pluralized label for "{count} documents found". Use as much plural forms (separated by "|") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)',message:"One document found|{count} documents found"},{count:t}))}(),p=function(){const e=(0,l._r)(),[t,r]=(0,n.useState)((()=>Object.entries(e).reduce(((e,t)=>{let[r,n]=t;return{...e,[r]:n.versions[0].name}}),{}))),i=Object.values(e).some((e=>e.versions.length>1));return{allDocsData:e,versioningEnabled:i,searchVersions:t,setSearchVersion:(e,t)=>r((r=>({...r,[e]:t})))}}(),[v,g]=(0,R.K)(),b={items:[],query:null,totalResults:null,totalPages:null,lastPage:null,hasMore:null,loading:null},[N,A]=(0,n.useReducer)(((e,t)=>{switch(t.type){case"reset":return b;case"loading":return{...e,loading:!0};case"update":return v!==t.value.query?e:{...t.value,items:0===t.value.lastPage?t.value.items:e.items.concat(t.value.items)};case"advance":{const t=e.totalPages>e.lastPage+1;return{...e,lastPage:t?e.lastPage+1:e.lastPage,hasMore:t}}default:return e}}),b),H=u()(t,r),S=s()(H,a,{hitsPerPage:15,advancedSyntax:!0,disjunctiveFacets:["language","docusaurus_tag"]});S.on("result",(e=>{let{results:{query:t,hits:r,page:n,nbHits:i,nbPages:a}}=e;if(""===t||!Array.isArray(r))return void A({type:"reset"});const s=e=>e.replace(/algolia-docsearch-suggestion--highlight/g,"search-result-match"),u=r.map((e=>{let{url:t,_highlightResult:{hierarchy:r},_snippetResult:n={}}=e;const i=Object.keys(r).map((e=>s(r[e].value)));return{title:i.pop(),url:c(t),summary:n.content?`${s(n.content.value)}...`:"",breadcrumbs:i}}));A({type:"update",value:{items:u,query:t,totalResults:i,totalPages:a,lastPage:n,hasMore:a>n+1,loading:!1}})}));const[T,Q]=(0,n.useState)(null),C=(0,n.useRef)(0),I=(0,n.useRef)(o.Z.canUseIntersectionObserver&&new IntersectionObserver((e=>{const{isIntersecting:t,boundingClientRect:{y:r}}=e[0];t&&C.current>r&&A({type:"advance"}),C.current=r}),{threshold:1})),k=()=>v?(0,j.I)({id:"theme.SearchPage.existingResultsTitle",message:'Search results for "{query}"',description:"The search page title for non-empty query"},{query:v}):(0,j.I)({id:"theme.SearchPage.emptyResultsTitle",message:"Search the documentation",description:"The search page title for empty query"}),D=(0,F.zX)((function(t){void 0===t&&(t=0),S.addDisjunctiveFacetRefinement("docusaurus_tag","default"),S.addDisjunctiveFacetRefinement("language",e),Object.entries(p.searchVersions).forEach((e=>{let[t,r]=e;S.addDisjunctiveFacetRefinement("docusaurus_tag",`docs-${t}-${r}`)})),S.setQuery(v).setPage(t).search()}));return(0,n.useEffect)((()=>{if(!T)return;const e=I.current;return e?(e.observe(T),()=>e.unobserve(T)):()=>!0}),[T]),(0,n.useEffect)((()=>{A({type:"reset"}),v&&(A({type:"loading"}),setTimeout((()=>{D()}),300))}),[v,p.searchVersions,D]),(0,n.useEffect)((()=>{N.lastPage&&0!==N.lastPage&&D(N.lastPage)}),[D,N.lastPage]),n.createElement(x.Z,null,n.createElement(h.Z,null,n.createElement("title",null,(0,P.p)(k())),n.createElement("meta",{property:"robots",content:"noindex, follow"})),n.createElement("div",{className:"container margin-vert--lg"},n.createElement("h1",null,k()),n.createElement("form",{className:"row",onSubmit:e=>e.preventDefault()},n.createElement("div",{className:(0,i.Z)("col",O.searchQueryColumn,{"col--9":p.versioningEnabled,"col--12":!p.versioningEnabled})},n.createElement("input",{type:"search",name:"q",className:O.searchQueryInput,placeholder:(0,j.I)({id:"theme.SearchPage.inputPlaceholder",message:"Type your search here",description:"The placeholder for search page input"}),"aria-label":(0,j.I)({id:"theme.SearchPage.inputLabel",message:"Search",description:"The ARIA label for search page input"}),onChange:e=>g(e.target.value),value:v,autoComplete:"off",autoFocus:!0})),p.versioningEnabled&&n.createElement(w,{docsSearchVersionsHelpers:p})),n.createElement("div",{className:"row"},n.createElement("div",{className:(0,i.Z)("col","col--8",O.searchResultsColumn)},!!N.totalResults&&d(N.totalResults)),n.createElement("div",{className:(0,i.Z)("col","col--4","text--right",O.searchLogoColumn)},n.createElement("a",{target:"_blank",rel:"noopener noreferrer",href:"https://www.algolia.com/","aria-label":(0,j.I)({id:"theme.SearchPage.algoliaLabel",message:"Search by Algolia",description:"The ARIA label for Algolia mention"})},n.createElement("svg",{viewBox:"0 0 168 24",className:O.algoliaLogo},n.createElement("g",{fill:"none"},n.createElement("path",{className:O.algoliaLogoPathFill,d:"M120.925 18.804c-4.386.02-4.386-3.54-4.386-4.106l-.007-13.336 2.675-.424v13.254c0 .322 0 2.358 1.718 2.364v2.248zm-10.846-2.18c.821 0 1.43-.047 1.855-.129v-2.719a6.334 6.334 0 0 0-1.574-.199 5.7 5.7 0 0 0-.897.069 2.699 2.699 0 0 0-.814.24c-.24.116-.439.28-.582.491-.15.212-.219.335-.219.656 0 .628.219.991.616 1.23s.938.362 1.615.362zm-.233-9.7c.883 0 1.629.109 2.231.328.602.218 1.088.525 1.444.915.363.396.609.922.76 1.483.157.56.232 1.175.232 1.85v6.874a32.5 32.5 0 0 1-1.868.314c-.834.123-1.772.185-2.813.185-.69 0-1.327-.069-1.895-.198a4.001 4.001 0 0 1-1.471-.636 3.085 3.085 0 0 1-.951-1.134c-.226-.465-.343-1.12-.343-1.803 0-.656.13-1.073.384-1.525a3.24 3.24 0 0 1 1.047-1.106c.445-.287.95-.492 1.532-.615a8.8 8.8 0 0 1 1.82-.185 8.404 8.404 0 0 1 1.972.24v-.438c0-.307-.035-.6-.11-.874a1.88 1.88 0 0 0-.384-.73 1.784 1.784 0 0 0-.724-.493 3.164 3.164 0 0 0-1.143-.205c-.616 0-1.177.075-1.69.164a7.735 7.735 0 0 0-1.26.307l-.321-2.192c.335-.117.834-.233 1.478-.349a10.98 10.98 0 0 1 2.073-.178zm52.842 9.626c.822 0 1.43-.048 1.854-.13V13.7a6.347 6.347 0 0 0-1.574-.199c-.294 0-.595.021-.896.069a2.7 2.7 0 0 0-.814.24 1.46 1.46 0 0 0-.582.491c-.15.212-.218.335-.218.656 0 .628.218.991.615 1.23.404.245.938.362 1.615.362zm-.226-9.694c.883 0 1.629.108 2.231.327.602.219 1.088.526 1.444.915.355.39.609.923.759 1.483a6.8 6.8 0 0 1 .233 1.852v6.873c-.41.088-1.034.19-1.868.314-.834.123-1.772.184-2.813.184-.69 0-1.327-.068-1.895-.198a4.001 4.001 0 0 1-1.471-.635 3.085 3.085 0 0 1-.951-1.134c-.226-.465-.343-1.12-.343-1.804 0-.656.13-1.073.384-1.524.26-.45.608-.82 1.047-1.107.445-.286.95-.491 1.532-.614a8.803 8.803 0 0 1 2.751-.13c.329.034.671.096 1.04.185v-.437a3.3 3.3 0 0 0-.109-.875 1.873 1.873 0 0 0-.384-.731 1.784 1.784 0 0 0-.724-.492 3.165 3.165 0 0 0-1.143-.205c-.616 0-1.177.075-1.69.164a7.75 7.75 0 0 0-1.26.307l-.321-2.193c.335-.116.834-.232 1.478-.348a11.633 11.633 0 0 1 2.073-.177zm-8.034-1.271a1.626 1.626 0 0 1-1.628-1.62c0-.895.725-1.62 1.628-1.62.904 0 1.63.725 1.63 1.62 0 .895-.733 1.62-1.63 1.62zm1.348 13.22h-2.689V7.27l2.69-.423v11.956zm-4.714 0c-4.386.02-4.386-3.54-4.386-4.107l-.008-13.336 2.676-.424v13.254c0 .322 0 2.358 1.718 2.364v2.248zm-8.698-5.903c0-1.156-.253-2.119-.746-2.788-.493-.677-1.183-1.01-2.067-1.01-.882 0-1.574.333-2.065 1.01-.493.676-.733 1.632-.733 2.788 0 1.168.246 1.953.74 2.63.492.683 1.183 1.018 2.066 1.018.882 0 1.574-.342 2.067-1.019.492-.683.738-1.46.738-2.63zm2.737-.007c0 .902-.13 1.584-.397 2.33a5.52 5.52 0 0 1-1.128 1.906 4.986 4.986 0 0 1-1.752 1.223c-.685.286-1.739.45-2.265.45-.528-.006-1.574-.157-2.252-.45a5.096 5.096 0 0 1-1.744-1.223c-.487-.527-.863-1.162-1.137-1.906a6.345 6.345 0 0 1-.41-2.33c0-.902.123-1.77.397-2.508a5.554 5.554 0 0 1 1.15-1.892 5.133 5.133 0 0 1 1.75-1.216c.679-.287 1.425-.423 2.232-.423.808 0 1.553.142 2.237.423a4.88 4.88 0 0 1 1.753 1.216 5.644 5.644 0 0 1 1.135 1.892c.287.738.431 1.606.431 2.508zm-20.138 0c0 1.12.246 2.363.738 2.882.493.52 1.13.78 1.91.78.424 0 .828-.062 1.204-.178.377-.116.677-.253.917-.417V9.33a10.476 10.476 0 0 0-1.766-.226c-.971-.028-1.71.37-2.23 1.004-.513.636-.773 1.75-.773 2.788zm7.438 5.274c0 1.824-.466 3.156-1.404 4.004-.936.846-2.367 1.27-4.296 1.27-.705 0-2.17-.137-3.34-.396l.431-2.118c.98.205 2.272.26 2.95.26 1.074 0 1.84-.219 2.299-.656.459-.437.684-1.086.684-1.948v-.437a8.07 8.07 0 0 1-1.047.397c-.43.13-.93.198-1.492.198-.739 0-1.41-.116-2.018-.349a4.206 4.206 0 0 1-1.567-1.025c-.431-.45-.774-1.017-1.013-1.694-.24-.677-.363-1.885-.363-2.773 0-.834.13-1.88.384-2.577.26-.696.629-1.298 1.129-1.796.493-.498 1.095-.881 1.8-1.162a6.605 6.605 0 0 1 2.428-.457c.87 0 1.67.109 2.45.24.78.129 1.444.265 1.985.415V18.17zM6.972 6.677v1.627c-.712-.446-1.52-.67-2.425-.67-.585 0-1.045.13-1.38.391a1.24 1.24 0 0 0-.502 1.03c0 .425.164.765.494 1.02.33.256.835.532 1.516.83.447.192.795.356 1.045.495.25.138.537.332.862.582.324.25.563.548.718.894.154.345.23.741.23 1.188 0 .947-.334 1.691-1.004 2.234-.67.542-1.537.814-2.601.814-1.18 0-2.16-.229-2.936-.686v-1.708c.84.628 1.814.942 2.92.942.585 0 1.048-.136 1.388-.407.34-.271.51-.646.51-1.125 0-.287-.1-.55-.302-.79-.203-.24-.42-.42-.655-.542-.234-.123-.585-.29-1.053-.503a61.27 61.27 0 0 1-.582-.271 13.67 13.67 0 0 1-.55-.287 4.275 4.275 0 0 1-.567-.351 6.92 6.92 0 0 1-.455-.4c-.18-.17-.31-.34-.39-.51-.08-.17-.155-.37-.224-.598a2.553 2.553 0 0 1-.104-.742c0-.915.333-1.638.998-2.17.664-.532 1.523-.798 2.576-.798.968 0 1.793.17 2.473.51zm7.468 5.696v-.287c-.022-.607-.187-1.088-.495-1.444-.309-.357-.75-.535-1.324-.535-.532 0-.99.194-1.373.583-.382.388-.622.949-.717 1.683h3.909zm1.005 2.792v1.404c-.596.34-1.383.51-2.362.51-1.255 0-2.255-.377-3-1.132-.744-.755-1.116-1.744-1.116-2.968 0-1.297.34-2.316 1.021-3.055.68-.74 1.548-1.11 2.6-1.11 1.033 0 1.852.323 2.458.966.606.644.91 1.572.91 2.784 0 .33-.033.676-.096 1.038h-5.314c.107.702.405 1.239.894 1.611.49.372 1.106.558 1.85.558.862 0 1.58-.202 2.155-.606zm6.605-1.77h-1.212c-.596 0-1.045.116-1.349.35-.303.234-.454.532-.454.894 0 .372.117.664.35.877.235.213.575.32 1.022.32.51 0 .912-.142 1.204-.424.293-.281.44-.651.44-1.108v-.91zm-4.068-2.554V9.325c.627-.361 1.457-.542 2.489-.542 2.116 0 3.175 1.026 3.175 3.08V17h-1.548v-.957c-.415.68-1.143 1.02-2.186 1.02-.766 0-1.38-.22-1.843-.661-.462-.442-.694-1.003-.694-1.684 0-.776.293-1.38.878-1.81.585-.431 1.404-.647 2.457-.647h1.34V11.8c0-.554-.133-.971-.399-1.253-.266-.282-.707-.423-1.324-.423a4.07 4.07 0 0 0-2.345.718zm9.333-1.93v1.42c.394-1 1.101-1.5 2.123-1.5.148 0 .313.016.494.048v1.531a1.885 1.885 0 0 0-.75-.143c-.542 0-.989.24-1.34.718-.351.479-.527 1.048-.527 1.707V17h-1.563V8.91h1.563zm5.01 4.084c.022.82.272 1.492.75 2.019.479.526 1.15.79 2.01.79.639 0 1.235-.176 1.788-.527v1.404c-.521.319-1.186.479-1.995.479-1.265 0-2.276-.4-3.031-1.197-.755-.798-1.133-1.792-1.133-2.984 0-1.16.38-2.151 1.14-2.975.761-.825 1.79-1.237 3.088-1.237.702 0 1.346.149 1.93.447v1.436a3.242 3.242 0 0 0-1.77-.495c-.84 0-1.513.266-2.019.798-.505.532-.758 1.213-.758 2.042zM40.24 5.72v4.579c.458-1 1.293-1.5 2.505-1.5.787 0 1.42.245 1.899.734.479.49.718 1.17.718 2.042V17h-1.564v-5.106c0-.553-.14-.98-.422-1.284-.282-.303-.652-.455-1.11-.455-.531 0-1.002.202-1.411.606-.41.405-.615 1.022-.615 1.851V17h-1.563V5.72h1.563zm14.966 10.02c.596 0 1.096-.253 1.5-.758.404-.506.606-1.157.606-1.955 0-.915-.202-1.62-.606-2.114-.404-.495-.92-.742-1.548-.742-.553 0-1.05.224-1.491.67-.442.447-.662 1.133-.662 2.058 0 .958.212 1.67.638 2.138.425.469.946.703 1.563.703zM53.004 5.72v4.42c.574-.894 1.388-1.341 2.44-1.341 1.022 0 1.857.383 2.506 1.149.649.766.973 1.781.973 3.047 0 1.138-.309 2.109-.925 2.912-.617.803-1.463 1.205-2.537 1.205-1.075 0-1.894-.447-2.457-1.34V17h-1.58V5.72h1.58zm9.908 11.104l-3.223-7.913h1.739l1.005 2.632 1.26 3.415c.096-.32.48-1.458 1.15-3.415l.909-2.632h1.66l-2.92 7.866c-.777 2.074-1.963 3.11-3.559 3.11a2.92 2.92 0 0 1-.734-.079v-1.34c.17.042.351.064.543.064 1.032 0 1.755-.57 2.17-1.708z"}),n.createElement("path",{fill:"#5468FF",d:"M78.988.938h16.594a2.968 2.968 0 0 1 2.966 2.966V20.5a2.967 2.967 0 0 1-2.966 2.964H78.988a2.967 2.967 0 0 1-2.966-2.964V3.897A2.961 2.961 0 0 1 78.988.938z"}),n.createElement("path",{fill:"white",d:"M89.632 5.967v-.772a.978.978 0 0 0-.978-.977h-2.28a.978.978 0 0 0-.978.977v.793c0 .088.082.15.171.13a7.127 7.127 0 0 1 1.984-.28c.65 0 1.295.088 1.917.259.082.02.164-.04.164-.13m-6.248 1.01l-.39-.389a.977.977 0 0 0-1.382 0l-.465.465a.973.973 0 0 0 0 1.38l.383.383c.062.061.15.047.205-.014.226-.307.472-.601.746-.874.281-.28.568-.526.883-.751.068-.042.075-.137.02-.2m4.16 2.453v3.341c0 .096.104.165.192.117l2.97-1.537c.068-.034.089-.117.055-.184a3.695 3.695 0 0 0-3.08-1.866c-.068 0-.136.054-.136.13m0 8.048a4.489 4.489 0 0 1-4.49-4.482 4.488 4.488 0 0 1 4.49-4.482 4.488 4.488 0 0 1 4.489 4.482 4.484 4.484 0 0 1-4.49 4.482m0-10.85a6.363 6.363 0 1 0 0 12.729 6.37 6.37 0 0 0 6.372-6.368 6.358 6.358 0 0 0-6.371-6.36"})))))),N.items.length>0?n.createElement("main",null,N.items.map(((e,t)=>{let{title:r,url:a,summary:s,breadcrumbs:c}=e;return n.createElement("article",{key:t,className:O.searchResultItem},n.createElement("h2",{className:O.searchResultItemHeading},n.createElement(f.Z,{to:a,dangerouslySetInnerHTML:{__html:r}})),c.length>0&&n.createElement("nav",{"aria-label":"breadcrumbs"},n.createElement("ul",{className:(0,i.Z)("breadcrumbs",O.searchResultItemPath)},c.map(((e,t)=>n.createElement("li",{key:t,className:"breadcrumbs__item",dangerouslySetInnerHTML:{__html:e}}))))),s&&n.createElement("p",{className:O.searchResultItemSummary,dangerouslySetInnerHTML:{__html:s}}))}))):[v&&!N.loading&&n.createElement("p",{key:"no-results"},n.createElement(j.Z,{id:"theme.SearchPage.noResultsText",description:"The paragraph for empty search result"},"No results were found")),!!N.loading&&n.createElement("div",{key:"spinner",className:O.loadingSpinner})],N.hasMore&&n.createElement("div",{className:O.loader,ref:Q},n.createElement(j.Z,{id:"theme.SearchPage.fetchingNewResults",description:"The paragraph for fetching new search results"},"Fetching new results..."))))}function A(){return n.createElement(b.FG,{className:"search-page-wrapper"},n.createElement(N,null))}}}]); \ No newline at end of file diff --git a/assets/js/1a4e3797.aef3ce1d.js.LICENSE.txt b/assets/js/1a4e3797.1587bb31.js.LICENSE.txt similarity index 100% rename from assets/js/1a4e3797.aef3ce1d.js.LICENSE.txt rename to assets/js/1a4e3797.1587bb31.js.LICENSE.txt diff --git a/assets/js/1a4e3797.aef3ce1d.js b/assets/js/1a4e3797.aef3ce1d.js deleted file mode 100644 index 495c30eb90..0000000000 --- a/assets/js/1a4e3797.aef3ce1d.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see 1a4e3797.aef3ce1d.js.LICENSE.txt */ -(self.webpackChunk=self.webpackChunk||[]).push([[7920],{7331:e=>{function t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function n(e){return"object"==typeof e&&null!==e}function i(e){return void 0===e}e.exports=t,t.prototype._events=void 0,t.prototype._maxListeners=void 0,t.defaultMaxListeners=10,t.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},t.prototype.emit=function(e){var t,a,s,c,u,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||n(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var h=new Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}if(i(a=this._events[e]))return!1;if(r(a))switch(arguments.length){case 1:a.call(this);break;case 2:a.call(this,arguments[1]);break;case 3:a.call(this,arguments[1],arguments[2]);break;default:c=Array.prototype.slice.call(arguments,1),a.apply(this,c)}else if(n(a))for(c=Array.prototype.slice.call(arguments,1),s=(o=a.slice()).length,u=0;u0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){if(!r(t))throw TypeError("listener must be a function");var n=!1;function i(){this.removeListener(e,i),n||(n=!0,t.apply(this,arguments))}return i.listener=t,this.on(e,i),this},t.prototype.removeListener=function(e,t){var i,a,s,c;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(i=this._events[e]).length,a=-1,i===t||r(i.listener)&&i.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(n(i)){for(c=s;c-- >0;)if(i[c]===t||i[c].listener&&i[c].listener===t){a=c;break}if(a<0)return this;1===i.length?(i.length=0,delete this._events[e]):i.splice(a,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},t.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},t.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},t.listenerCount=function(e,t){return e.listenerCount(t)}},8131:(e,t,r)=>{"use strict";var n=r(9374),i=r(7775),a=r(3076);function s(e,t,r,i){return new n(e,t,r,i)}s.version=r(4336),s.AlgoliaSearchHelper=n,s.SearchParameters=i,s.SearchResults=a,e.exports=s},8078:(e,t,r)=>{"use strict";var n=r(7331);function i(e,t){this.main=e,this.fn=t,this.lastResults=null}r(4853)(i,n),i.prototype.detach=function(){this.removeAllListeners(),this.main.detachDerivedHelper(this)},i.prototype.getModifiedState=function(e){return this.fn(e)},e.exports=i},2437:(e,t,r)=>{"use strict";var n=r(2344),i=r(116),a=r(9803),s={addRefinement:function(e,t,r){if(s.isRefined(e,t,r))return e;var i=""+r,a=e[t]?e[t].concat(i):[i],c={};return c[t]=a,n({},c,e)},removeRefinement:function(e,t,r){if(void 0===r)return s.clearRefinement(e,(function(e,r){return t===r}));var n=""+r;return s.clearRefinement(e,(function(e,r){return t===r&&n===e}))},toggleRefinement:function(e,t,r){if(void 0===r)throw new Error("toggleRefinement should be used with a value");return s.isRefined(e,t,r)?s.removeRefinement(e,t,r):s.addRefinement(e,t,r)},clearRefinement:function(e,t,r){if(void 0===t)return i(e)?{}:e;if("string"==typeof t)return a(e,[t]);if("function"==typeof t){var n=!1,s=Object.keys(e).reduce((function(i,a){var s=e[a]||[],c=s.filter((function(e){return!t(e,a,r)}));return c.length!==s.length&&(n=!0),i[a]=c,i}),{});return n?s:e}},isRefined:function(e,t,r){var n=Boolean(e[t])&&e[t].length>0;if(void 0===r||!n)return n;var i=""+r;return-1!==e[t].indexOf(i)}};e.exports=s},7775:(e,t,r)=>{"use strict";var n=r(2344),i=r(7888),a=r(2686),s=r(185),c=r(116),u=r(9803),o=r(8023),h=r(6801),f=r(2437);function l(e,t){return Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((function(e,r){return l(t[r],e)})):e===t}function m(e){var t=e?m._parseNumbers(e):{};void 0===t.userToken||h(t.userToken)||console.warn("[algoliasearch-helper] The `userToken` parameter is invalid. This can lead to wrong analytics.\n - Format: [a-zA-Z0-9_-]{1,64}"),this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{};var r=this;Object.keys(t).forEach((function(e){var n=-1!==m.PARAMETERS.indexOf(e),i=void 0!==t[e];!n&&i&&(r[e]=t[e])}))}m.PARAMETERS=Object.keys(new m),m._parseNumbers=function(e){if(e instanceof m)return e;var t={};if(["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"].forEach((function(r){var n=e[r];if("string"==typeof n){var i=parseFloat(n);t[r]=isNaN(i)?n:i}})),Array.isArray(e.insideBoundingBox)&&(t.insideBoundingBox=e.insideBoundingBox.map((function(e){return Array.isArray(e)?e.map((function(e){return parseFloat(e)})):e}))),e.numericRefinements){var r={};Object.keys(e.numericRefinements).forEach((function(t){var n=e.numericRefinements[t]||{};r[t]={},Object.keys(n).forEach((function(e){var i=n[e].map((function(e){return Array.isArray(e)?e.map((function(e){return"string"==typeof e?parseFloat(e):e})):"string"==typeof e?parseFloat(e):e}));r[t][e]=i}))})),t.numericRefinements=r}return s({},e,t)},m.make=function(e){var t=new m(e);return(e.hierarchicalFacets||[]).forEach((function(e){if(e.rootPath){var r=t.getHierarchicalRefinement(e.name);r.length>0&&0!==r[0].indexOf(e.rootPath)&&(t=t.clearRefinements(e.name)),0===(r=t.getHierarchicalRefinement(e.name)).length&&(t=t.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}})),t},m.validate=function(e,t){var r=t||{};return e.tagFilters&&r.tagRefinements&&r.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&r.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&r.numericRefinements&&c(r.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):c(e.numericRefinements)&&r.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},m.prototype={constructor:m,clearRefinements:function(e){var t={numericRefinements:this._clearNumericRefinements(e),facetsRefinements:f.clearRefinement(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:f.clearRefinement(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:f.clearRefinement(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:f.clearRefinement(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")};return t.numericRefinements===this.numericRefinements&&t.facetsRefinements===this.facetsRefinements&&t.facetsExcludes===this.facetsExcludes&&t.disjunctiveFacetsRefinements===this.disjunctiveFacetsRefinements&&t.hierarchicalFacetsRefinements===this.hierarchicalFacetsRefinements?this:this.setQueryParameters(t)},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e})},addNumericRefinement:function(e,t,r){var n=o(r);if(this.isNumericRefined(e,t,n))return this;var i=s({},this.numericRefinements);return i[e]=s({},i[e]),i[e][t]?(i[e][t]=i[e][t].slice(),i[e][t].push(n)):i[e][t]=[n],this.setQueryParameters({numericRefinements:i})},getConjunctiveRefinements:function(e){return this.isConjunctiveFacet(e)&&this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){return this.isDisjunctiveFacet(e)&&this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){return this.isConjunctiveFacet(e)&&this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,r){var n=r;return void 0!==n?this.isNumericRefined(e,t,n)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(r,i){return i===e&&r.op===t&&l(r.val,o(n))}))}):this:void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(r,n){return n===e&&r.op===t}))}):this:this.isNumericRefined(e)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements((function(t,r){return r===e}))}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){if(void 0===e)return c(this.numericRefinements)?{}:this.numericRefinements;if("string"==typeof e)return u(this.numericRefinements,[e]);if("function"==typeof e){var t=!1,r=this.numericRefinements,n=Object.keys(r).reduce((function(n,i){var a=r[i],s={};return a=a||{},Object.keys(a).forEach((function(r){var n=a[r]||[],c=[];n.forEach((function(t){e({val:t,op:r},i,"numeric")||c.push(t)})),c.length!==n.length&&(t=!0),s[r]=c})),n[i]=s,n}),{});return t?n:this.numericRefinements}},addFacet:function(e){return this.isConjunctiveFacet(e)?this:this.setQueryParameters({facets:this.facets.concat([e])})},addDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this:this.setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.concat([e])})},addHierarchicalFacet:function(e){if(this.isHierarchicalFacet(e.name))throw new Error("Cannot declare two hierarchical facets with the same name: `"+e.name+"`");return this.setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.concat([e])})},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({facetsRefinements:f.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({facetsExcludes:f.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return f.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({disjunctiveFacetsRefinements:f.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacet:function(e){return this.isConjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({facets:this.facets.filter((function(t){return t!==e}))}):this},removeDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.filter((function(t){return t!==e}))}):this},removeHierarchicalFacet:function(e){return this.isHierarchicalFacet(e)?this.clearRefinements(e).setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.filter((function(t){return t.name!==e}))}):this},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({facetsRefinements:f.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return f.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({facetsExcludes:f.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return f.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({disjunctiveFacetsRefinements:f.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.filter((function(t){return t!==e}))};return this.setQueryParameters(t)},toggleRefinement:function(e,t){return this.toggleFacetRefinement(e,t)},toggleFacetRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleConjunctiveFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleConjunctiveFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsRefinements:f.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsExcludes:f.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({disjunctiveFacetsRefinements:f.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),i={};return void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+r))?-1===t.indexOf(r)?i[e]=[]:i[e]=[t.slice(0,t.lastIndexOf(r))]:i[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:n({},i,this.hierarchicalFacetsRefinements)})},addHierarchicalFacetRefinement:function(e,t){if(this.isHierarchicalFacetRefined(e))throw new Error(e+" is already refined.");if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration.");var r={};return r[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:n({},r,this.hierarchicalFacetsRefinements)})},removeHierarchicalFacetRefinement:function(e){if(!this.isHierarchicalFacetRefined(e))return this;var t={};return t[e]=[],this.setQueryParameters({hierarchicalFacetsRefinements:n({},t,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return this.disjunctiveFacets.indexOf(e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return this.facets.indexOf(e)>-1},isFacetRefined:function(e,t){return!!this.isConjunctiveFacet(e)&&f.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){return!!this.isConjunctiveFacet(e)&&f.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){return!!this.isDisjunctiveFacet(e)&&f.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))return!1;var r=this.getHierarchicalRefinement(e);return t?-1!==r.indexOf(t):r.length>0},isNumericRefined:function(e,t,r){if(void 0===r&&void 0===t)return Boolean(this.numericRefinements[e]);var n=this.numericRefinements[e]&&void 0!==this.numericRefinements[e][t];if(void 0===r||!n)return n;var a,s,c=o(r),u=void 0!==(a=this.numericRefinements[e][t],s=c,i(a,(function(e){return l(e,s)})));return n&&u},isTagRefined:function(e){return-1!==this.tagRefinements.indexOf(e)},getRefinedDisjunctiveFacets:function(){var e=this,t=a(Object.keys(this.numericRefinements).filter((function(t){return Object.keys(e.numericRefinements[t]).length>0})),this.disjunctiveFacets);return Object.keys(this.disjunctiveFacetsRefinements).filter((function(t){return e.disjunctiveFacetsRefinements[t].length>0})).concat(t).concat(this.getRefinedHierarchicalFacets()).sort()},getRefinedHierarchicalFacets:function(){var e=this;return a(this.hierarchicalFacets.map((function(e){return e.name})),Object.keys(this.hierarchicalFacetsRefinements).filter((function(t){return e.hierarchicalFacetsRefinements[t].length>0}))).sort()},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return this.disjunctiveFacets.filter((function(t){return-1===e.indexOf(t)}))},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","hierarchicalFacets","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={},r=this;return Object.keys(this).forEach((function(n){var i=r[n];-1===e.indexOf(n)&&void 0!==i&&(t[n]=i)})),t},setQueryParameter:function(e,t){if(this[e]===t)return this;var r={};return r[e]=t,this.setQueryParameters(r)},setQueryParameters:function(e){if(!e)return this;var t=m.validate(this,e);if(t)throw t;var r=this,n=m._parseNumbers(e),i=Object.keys(this).reduce((function(e,t){return e[t]=r[t],e}),{}),a=Object.keys(n).reduce((function(e,t){var r=void 0!==e[t],i=void 0!==n[t];return r&&!i?u(e,[t]):(i&&(e[t]=n[t]),e)}),i);return new this.constructor(a)},resetPage:function(){return void 0===this.page?this:this.setPage(0)},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"!=typeof e.showParentLevel||e.showParentLevel},getHierarchicalFacetByName:function(e){return i(this.hierarchicalFacets,(function(t){return t.name===e}))},getHierarchicalFacetBreadcrumb:function(e){if(!this.isHierarchicalFacet(e))return[];var t=this.getHierarchicalRefinement(e)[0];if(!t)return[];var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e));return t.split(r).map((function(e){return e.trim()}))},toString:function(){return JSON.stringify(this,null,2)}},e.exports=m},210:(e,t,r)=>{"use strict";e.exports=function(e){return function(t,r){var n=e.hierarchicalFacets[r],o=e.hierarchicalFacetsRefinements[n.name]&&e.hierarchicalFacetsRefinements[n.name][0]||"",h=e._getHierarchicalFacetSeparator(n),f=e._getHierarchicalRootPath(n),l=e._getHierarchicalShowParentLevel(n),m=a(e._getHierarchicalFacetSortBy(n)),d=t.every((function(e){return e.exhaustive})),p=function(e,t,r,n,a){return function(o,h,f){var l=o;if(f>0){var m=0;for(l=o;m{"use strict";var n=r(4587),i=r(2344),a=r(4039),s=r(7888),c=r(9725),u=r(2293),o=r(185),h=r(2148),f=a.escapeFacetValue,l=a.unescapeFacetValue,m=r(210);function d(e){var t={};return e.forEach((function(e,r){t[e]=r})),t}function p(e,t,r){t&&t[r]&&(e.stats=t[r])}function v(e,t,r){var a=t[0];this._rawResults=t;var u=this;Object.keys(a).forEach((function(e){u[e]=a[e]}));var h=o({persistHierarchicalRootCount:!1},r);Object.keys(h).forEach((function(e){u[e]=h[e]})),this.processingTimeMS=t.reduce((function(e,t){return void 0===t.processingTimeMS?e:e+t.processingTimeMS}),0),this.disjunctiveFacets=[],this.hierarchicalFacets=e.hierarchicalFacets.map((function(){return[]})),this.facets=[];var f=e.getRefinedDisjunctiveFacets(),v=d(e.facets),g=d(e.disjunctiveFacets),y=1,R=a.facets||{};Object.keys(R).forEach((function(t){var r,n,i=R[t],o=(r=e.hierarchicalFacets,n=t,s(r,(function(e){return(e.attributes||[]).indexOf(n)>-1})));if(o){var h=o.attributes.indexOf(t),f=c(e.hierarchicalFacets,(function(e){return e.name===o.name}));u.hierarchicalFacets[f][h]={attribute:t,data:i,exhaustive:a.exhaustiveFacetsCount}}else{var l,m=-1!==e.disjunctiveFacets.indexOf(t),d=-1!==e.facets.indexOf(t);m&&(l=g[t],u.disjunctiveFacets[l]={name:t,data:i,exhaustive:a.exhaustiveFacetsCount},p(u.disjunctiveFacets[l],a.facets_stats,t)),d&&(l=v[t],u.facets[l]={name:t,data:i,exhaustive:a.exhaustiveFacetsCount},p(u.facets[l],a.facets_stats,t))}})),this.hierarchicalFacets=n(this.hierarchicalFacets),f.forEach((function(r){var n=t[y],s=n&&n.facets?n.facets:{},h=e.getHierarchicalFacetByName(r);Object.keys(s).forEach((function(t){var r,f=s[t];if(h){r=c(e.hierarchicalFacets,(function(e){return e.name===h.name}));var m=c(u.hierarchicalFacets[r],(function(e){return e.attribute===t}));if(-1===m)return;u.hierarchicalFacets[r][m].data=o({},u.hierarchicalFacets[r][m].data,f)}else{r=g[t];var d=a.facets&&a.facets[t]||{};u.disjunctiveFacets[r]={name:t,data:i({},f,d),exhaustive:n.exhaustiveFacetsCount},p(u.disjunctiveFacets[r],n.facets_stats,t),e.disjunctiveFacetsRefinements[t]&&e.disjunctiveFacetsRefinements[t].forEach((function(n){!u.disjunctiveFacets[r].data[n]&&e.disjunctiveFacetsRefinements[t].indexOf(l(n))>-1&&(u.disjunctiveFacets[r].data[n]=0)}))}})),y++})),e.getRefinedHierarchicalFacets().forEach((function(r){var n=e.getHierarchicalFacetByName(r),a=e._getHierarchicalFacetSeparator(n),s=e.getHierarchicalRefinement(r);0===s.length||s[0].split(a).length<2||t.slice(y).forEach((function(t){var r=t&&t.facets?t.facets:{};Object.keys(r).forEach((function(t){var o=r[t],h=c(e.hierarchicalFacets,(function(e){return e.name===n.name})),f=c(u.hierarchicalFacets[h],(function(e){return e.attribute===t}));if(-1!==f){var l={};if(s.length>0&&!u.persistHierarchicalRootCount){var m=s[0].split(a)[0];l[m]=u.hierarchicalFacets[h][f].data[m]}u.hierarchicalFacets[h][f].data=i(l,o,u.hierarchicalFacets[h][f].data)}})),y++}))})),Object.keys(e.facetsExcludes).forEach((function(t){var r=e.facetsExcludes[t],n=v[t];u.facets[n]={name:t,data:R[t],exhaustive:a.exhaustiveFacetsCount},r.forEach((function(e){u.facets[n]=u.facets[n]||{name:t},u.facets[n].data=u.facets[n].data||{},u.facets[n].data[e]=0}))})),this.hierarchicalFacets=this.hierarchicalFacets.map(m(e)),this.facets=n(this.facets),this.disjunctiveFacets=n(this.disjunctiveFacets),this._state=e}function g(e,t){function r(e){return e.name===t}if(e._state.isConjunctiveFacet(t)){var n=s(e.facets,r);return n?Object.keys(n.data).map((function(r){var i=f(r);return{name:r,escapedValue:i,count:n.data[r],isRefined:e._state.isFacetRefined(t,i),isExcluded:e._state.isExcludeRefined(t,r)}})):[]}if(e._state.isDisjunctiveFacet(t)){var i=s(e.disjunctiveFacets,r);return i?Object.keys(i.data).map((function(r){var n=f(r);return{name:r,escapedValue:n,count:i.data[r],isRefined:e._state.isDisjunctiveFacetRefined(t,n)}})):[]}if(e._state.isHierarchicalFacet(t)){var a=s(e.hierarchicalFacets,r);if(!a)return a;var c=e._state.getHierarchicalFacetByName(t),u=e._state._getHierarchicalFacetSeparator(c),o=l(e._state.getHierarchicalRefinement(t)[0]||"");0===o.indexOf(c.rootPath)&&(o=o.replace(c.rootPath+u,""));var h=o.split(u);return h.unshift(t),y(a,h,0),a}}function y(e,t,r){e.isRefined=e.name===t[r],e.data&&e.data.forEach((function(e){y(e,t,r+1)}))}function R(e,t,r,n){if(n=n||0,Array.isArray(t))return e(t,r[n]);if(!t.data||0===t.data.length)return t;var a=t.data.map((function(t){return R(e,t,r,n+1)})),s=e(a,r[n]);return i({data:s},t)}function F(e,t){var r=s(e,(function(e){return e.name===t}));return r&&r.stats}function b(e,t,r,n,i){var a=s(i,(function(e){return e.name===r})),c=a&&a.data&&a.data[n]?a.data[n]:0,u=a&&a.exhaustive||!1;return{type:t,attributeName:r,name:n,count:c,exhaustive:u}}v.prototype.getFacetByName=function(e){function t(t){return t.name===e}return s(this.facets,t)||s(this.disjunctiveFacets,t)||s(this.hierarchicalFacets,t)},v.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],v.prototype.getFacetValues=function(e,t){var r=g(this,e);if(r){var n,a=i({},t,{sortBy:v.DEFAULT_SORT,facetOrdering:!(t&&t.sortBy)}),s=this;if(Array.isArray(r))n=[e];else n=s._state.getHierarchicalFacetByName(r.name).attributes;return R((function(e,t){if(a.facetOrdering){var r=function(e,t){return e.renderingContent&&e.renderingContent.facetOrdering&&e.renderingContent.facetOrdering.values&&e.renderingContent.facetOrdering.values[t]}(s,t);if(r)return function(e,t){var r=[],n=[],i=(t.order||[]).reduce((function(e,t,r){return e[t]=r,e}),{});e.forEach((function(e){var t=e.path||e.name;void 0!==i[t]?r[i[t]]=e:n.push(e)})),r=r.filter((function(e){return e}));var a,s=t.sortRemainingBy;return"hidden"===s?r:(a="alpha"===s?[["path","name"],["asc","asc"]]:[["count"],["desc"]],r.concat(h(n,a[0],a[1])))}(e,r)}if(Array.isArray(a.sortBy)){var n=u(a.sortBy,v.DEFAULT_SORT);return h(e,n[0],n[1])}if("function"==typeof a.sortBy)return function(e,t){return t.sort(e)}(a.sortBy,e);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")}),r,n)}},v.prototype.getFacetStats=function(e){return this._state.isConjunctiveFacet(e)?F(this.facets,e):this._state.isDisjunctiveFacet(e)?F(this.disjunctiveFacets,e):void 0},v.prototype.getRefinements=function(){var e=this._state,t=this,r=[];return Object.keys(e.facetsRefinements).forEach((function(n){e.facetsRefinements[n].forEach((function(i){r.push(b(e,"facet",n,i,t.facets))}))})),Object.keys(e.facetsExcludes).forEach((function(n){e.facetsExcludes[n].forEach((function(i){r.push(b(e,"exclude",n,i,t.facets))}))})),Object.keys(e.disjunctiveFacetsRefinements).forEach((function(n){e.disjunctiveFacetsRefinements[n].forEach((function(i){r.push(b(e,"disjunctive",n,i,t.disjunctiveFacets))}))})),Object.keys(e.hierarchicalFacetsRefinements).forEach((function(n){e.hierarchicalFacetsRefinements[n].forEach((function(i){r.push(function(e,t,r,n){var i=e.getHierarchicalFacetByName(t),a=e._getHierarchicalFacetSeparator(i),c=r.split(a),u=s(n,(function(e){return e.name===t})),o=c.reduce((function(e,t){var r=e&&s(e.data,(function(e){return e.name===t}));return void 0!==r?r:e}),u),h=o&&o.count||0,f=o&&o.exhaustive||!1,l=o&&o.path||"";return{type:"hierarchical",attributeName:t,name:l,count:h,exhaustive:f}}(e,n,i,t.hierarchicalFacets))}))})),Object.keys(e.numericRefinements).forEach((function(t){var n=e.numericRefinements[t];Object.keys(n).forEach((function(e){n[e].forEach((function(n){r.push({type:"numeric",attributeName:t,name:n,numericValue:n,operator:e})}))}))})),e.tagRefinements.forEach((function(e){r.push({type:"tag",attributeName:"_tags",name:e})})),r},e.exports=v},9374:(e,t,r)=>{"use strict";var n=r(7331),i=r(8078),a=r(4039).escapeFacetValue,s=r(4853),c=r(185),u=r(116),o=r(9803),h=r(6394),f=r(7775),l=r(3076),m=r(4336);function d(e,t,r,n){"function"==typeof e.addAlgoliaAgent&&e.addAlgoliaAgent("JS Helper ("+m+")"),this.setClient(e);var i=r||{};i.index=t,this.state=f.make(i),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1,this.derivedHelpers=[],this._currentNbQueries=0,this._searchResultsOptions=n}function p(e){if(e<0)throw new Error("Page requested below 0.");return this._change({state:this.state.setPage(e),isPageReset:!1}),this}function v(){return this.state.page}s(d,n),d.prototype.search=function(){return this._search({onlyWithDerivedHelpers:!1}),this},d.prototype.searchOnlyWithDerivedHelpers=function(){return this._search({onlyWithDerivedHelpers:!0}),this},d.prototype.getQuery=function(){var e=this.state;return h._getHitsSearchParams(e)},d.prototype.searchOnce=function(e,t){var r=e?this.state.setQueryParameters(e):this.state,n=h._getQueries(r.index,r),i=this;if(this._currentNbQueries++,this.emit("searchOnce",{state:r}),!t)return this.client.search(n).then((function(e){return i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),{content:new l(r,e.results),state:r,_originalResponse:e}}),(function(e){throw i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),e}));this.client.search(n).then((function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(null,new l(r,e.results),r)})).catch((function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(e,null,r)}))},d.prototype.findAnswers=function(e){console.warn("[algoliasearch-helper] answers is no longer supported");var t=this.state,r=this.derivedHelpers[0];if(!r)return Promise.resolve([]);var n=r.getModifiedState(t),i=c({attributesForPrediction:e.attributesForPrediction,nbHits:e.nbHits},{params:o(h._getHitsSearchParams(n),["attributesToSnippet","hitsPerPage","restrictSearchableAttributes","snippetEllipsisText"])}),a="search for answers was called, but this client does not have a function client.initIndex(index).findAnswers";if("function"!=typeof this.client.initIndex)throw new Error(a);var s=this.client.initIndex(n.index);if("function"!=typeof s.findAnswers)throw new Error(a);return s.findAnswers(n.query,e.queryLanguages,i)},d.prototype.searchForFacetValues=function(e,t,r,n){var i="function"==typeof this.client.searchForFacetValues,s="function"==typeof this.client.initIndex;if(!i&&!s&&"function"!=typeof this.client.search)throw new Error("search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues");var c=this.state.setQueryParameters(n||{}),u=c.isDisjunctiveFacet(e),o=h.getSearchForFacetQuery(e,t,r,c);this._currentNbQueries++;var f,l=this;return i?f=this.client.searchForFacetValues([{indexName:c.index,params:o}]):s?f=this.client.initIndex(c.index).searchForFacetValues(o):(delete o.facetName,f=this.client.search([{type:"facet",facet:e,indexName:c.index,params:o}]).then((function(e){return e.results[0]}))),this.emit("searchForFacetValues",{state:c,facet:e,query:t}),f.then((function(t){return l._currentNbQueries--,0===l._currentNbQueries&&l.emit("searchQueueEmpty"),(t=Array.isArray(t)?t[0]:t).facetHits.forEach((function(t){t.escapedValue=a(t.value),t.isRefined=u?c.isDisjunctiveFacetRefined(e,t.escapedValue):c.isFacetRefined(e,t.escapedValue)})),t}),(function(e){throw l._currentNbQueries--,0===l._currentNbQueries&&l.emit("searchQueueEmpty"),e}))},d.prototype.setQuery=function(e){return this._change({state:this.state.resetPage().setQuery(e),isPageReset:!0}),this},d.prototype.clearRefinements=function(e){return this._change({state:this.state.resetPage().clearRefinements(e),isPageReset:!0}),this},d.prototype.clearTags=function(){return this._change({state:this.state.resetPage().clearTags(),isPageReset:!0}),this},d.prototype.addDisjunctiveFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addDisjunctiveFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},d.prototype.addHierarchicalFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addHierarchicalFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addNumericRefinement=function(e,t,r){return this._change({state:this.state.resetPage().addNumericRefinement(e,t,r),isPageReset:!0}),this},d.prototype.addFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().addFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},d.prototype.addFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().addExcludeRefinement(e,t),isPageReset:!0}),this},d.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},d.prototype.addTag=function(e){return this._change({state:this.state.resetPage().addTagRefinement(e),isPageReset:!0}),this},d.prototype.removeNumericRefinement=function(e,t,r){return this._change({state:this.state.resetPage().removeNumericRefinement(e,t,r),isPageReset:!0}),this},d.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().removeDisjunctiveFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},d.prototype.removeHierarchicalFacetRefinement=function(e){return this._change({state:this.state.resetPage().removeHierarchicalFacetRefinement(e),isPageReset:!0}),this},d.prototype.removeFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().removeFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},d.prototype.removeFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().removeExcludeRefinement(e,t),isPageReset:!0}),this},d.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},d.prototype.removeTag=function(e){return this._change({state:this.state.resetPage().removeTagRefinement(e),isPageReset:!0}),this},d.prototype.toggleFacetExclusion=function(e,t){return this._change({state:this.state.resetPage().toggleExcludeFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},d.prototype.toggleRefinement=function(e,t){return this.toggleFacetRefinement(e,t)},d.prototype.toggleFacetRefinement=function(e,t){return this._change({state:this.state.resetPage().toggleFacetRefinement(e,t),isPageReset:!0}),this},d.prototype.toggleRefine=function(){return this.toggleFacetRefinement.apply(this,arguments)},d.prototype.toggleTag=function(e){return this._change({state:this.state.resetPage().toggleTagRefinement(e),isPageReset:!0}),this},d.prototype.nextPage=function(){var e=this.state.page||0;return this.setPage(e+1)},d.prototype.previousPage=function(){var e=this.state.page||0;return this.setPage(e-1)},d.prototype.setCurrentPage=p,d.prototype.setPage=p,d.prototype.setIndex=function(e){return this._change({state:this.state.resetPage().setIndex(e),isPageReset:!0}),this},d.prototype.setQueryParameter=function(e,t){return this._change({state:this.state.resetPage().setQueryParameter(e,t),isPageReset:!0}),this},d.prototype.setState=function(e){return this._change({state:f.make(e),isPageReset:!1}),this},d.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new f(e),this},d.prototype.hasRefinements=function(e){return!!u(this.state.getNumericRefinements(e))||(this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):!!this.state.isHierarchicalFacet(e)&&this.state.isHierarchicalFacetRefined(e))},d.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},d.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},d.prototype.hasTag=function(e){return this.state.isTagRefined(e)},d.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},d.prototype.getIndex=function(){return this.state.index},d.prototype.getCurrentPage=v,d.prototype.getPage=v,d.prototype.getTags=function(){return this.state.tagRefinements},d.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e))this.state.getConjunctiveRefinements(e).forEach((function(e){t.push({value:e,type:"conjunctive"})})),this.state.getExcludeRefinements(e).forEach((function(e){t.push({value:e,type:"exclude"})}));else if(this.state.isDisjunctiveFacet(e)){this.state.getDisjunctiveRefinements(e).forEach((function(e){t.push({value:e,type:"disjunctive"})}))}var r=this.state.getNumericRefinements(e);return Object.keys(r).forEach((function(e){var n=r[e];t.push({value:n,operator:e,type:"numeric"})})),t},d.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},d.prototype.getHierarchicalFacetBreadcrumb=function(e){return this.state.getHierarchicalFacetBreadcrumb(e)},d.prototype._search=function(e){var t=this.state,r=[],n=[];e.onlyWithDerivedHelpers||(n=h._getQueries(t.index,t),r.push({state:t,queriesCount:n.length,helper:this}),this.emit("search",{state:t,results:this.lastResults}));var i=this.derivedHelpers.map((function(e){var n=e.getModifiedState(t),i=n.index?h._getQueries(n.index,n):[];return r.push({state:n,queriesCount:i.length,helper:e}),e.emit("search",{state:n,results:e.lastResults}),i})),a=Array.prototype.concat.apply(n,i),s=this._queryId++;if(this._currentNbQueries++,!a.length)return Promise.resolve({results:[]}).then(this._dispatchAlgoliaResponse.bind(this,r,s));try{this.client.search(a).then(this._dispatchAlgoliaResponse.bind(this,r,s)).catch(this._dispatchAlgoliaError.bind(this,s))}catch(c){this.emit("error",{error:c})}},d.prototype._dispatchAlgoliaResponse=function(e,t,r){var n=this;if(!(t0},d.prototype._change=function(e){var t=e.state,r=e.isPageReset;t!==this.state&&(this.state=t,this.emit("change",{state:this.state,results:this.lastResults,isPageReset:r}))},d.prototype.clearCache=function(){return this.client.clearCache&&this.client.clearCache(),this},d.prototype.setClient=function(e){return this.client===e||("function"==typeof e.addAlgoliaAgent&&e.addAlgoliaAgent("JS Helper ("+m+")"),this.client=e),this},d.prototype.getClient=function(){return this.client},d.prototype.derive=function(e){var t=new i(this,e);return this.derivedHelpers.push(t),t},d.prototype.detachDerivedHelper=function(e){var t=this.derivedHelpers.indexOf(e);if(-1===t)throw new Error("Derived helper already detached");this.derivedHelpers.splice(t,1)},d.prototype.hasPendingRequests=function(){return this._currentNbQueries>0},e.exports=d},4587:e=>{"use strict";e.exports=function(e){return Array.isArray(e)?e.filter(Boolean):[]}},2344:e=>{"use strict";e.exports=function(){return Array.prototype.slice.call(arguments).reduceRight((function(e,t){return Object.keys(Object(t)).forEach((function(r){void 0!==t[r]&&(void 0!==e[r]&&delete e[r],e[r]=t[r])})),e}),{})}},4039:e=>{"use strict";e.exports={escapeFacetValue:function(e){return"string"!=typeof e?e:String(e).replace(/^-/,"\\-")},unescapeFacetValue:function(e){return"string"!=typeof e?e:e.replace(/^\\-/,"-")}}},7888:e=>{"use strict";e.exports=function(e,t){if(Array.isArray(e))for(var r=0;r{"use strict";e.exports=function(e,t){if(!Array.isArray(e))return-1;for(var r=0;r{"use strict";var n=r(7888);e.exports=function(e,t){var r=(t||[]).map((function(e){return e.split(":")}));return e.reduce((function(e,t){var i=t.split(":"),a=n(r,(function(e){return e[0]===i[0]}));return i.length>1||!a?(e[0].push(i[0]),e[1].push(i[1]),e):(e[0].push(a[0]),e[1].push(a[1]),e)}),[[],[]])}},4853:e=>{"use strict";e.exports=function(e,t){e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},2686:e=>{"use strict";e.exports=function(e,t){return e.filter((function(r,n){return t.indexOf(r)>-1&&e.indexOf(r)===n}))}},185:e=>{"use strict";function t(e){return"function"==typeof e||Array.isArray(e)||"[object Object]"===Object.prototype.toString.call(e)}function r(e,n){if(e===n)return e;for(var i in n)if(Object.prototype.hasOwnProperty.call(n,i)&&"__proto__"!==i&&"constructor"!==i){var a=n[i],s=e[i];void 0!==s&&void 0===a||(t(s)&&t(a)?e[i]=r(s,a):e[i]="object"==typeof(c=a)&&null!==c?r(Array.isArray(c)?[]:{},c):c)}var c;return e}e.exports=function(e){t(e)||(e={});for(var n=1,i=arguments.length;n{"use strict";e.exports=function(e){return e&&Object.keys(e).length>0}},9803:e=>{"use strict";e.exports=function(e,t){if(null===e)return{};var r,n,i={},a=Object.keys(e);for(n=0;n=0||(i[r]=e[r]);return i}},2148:e=>{"use strict";function t(e,t){if(e!==t){var r=void 0!==e,n=null===e,i=void 0!==t,a=null===t;if(!a&&e>t||n&&i||!r)return 1;if(!n&&e=n.length?a:"desc"===n[i]?-a:a}return e.index-r.index})),i.map((function(e){return e.value}))}},8023:e=>{"use strict";e.exports=function e(t){if("number"==typeof t)return t;if("string"==typeof t)return parseFloat(t);if(Array.isArray(t))return t.map(e);throw new Error("The value should be a number, a parsable string or an array of those.")}},6394:(e,t,r)=>{"use strict";var n=r(185);function i(e){return Object.keys(e).sort().reduce((function(t,r){return t[r]=e[r],t}),{})}var a={_getQueries:function(e,t){var r=[];return r.push({indexName:e,params:a._getHitsSearchParams(t)}),t.getRefinedDisjunctiveFacets().forEach((function(n){r.push({indexName:e,params:a._getDisjunctiveFacetSearchParams(t,n)})})),t.getRefinedHierarchicalFacets().forEach((function(n){var i=t.getHierarchicalFacetByName(n),s=t.getHierarchicalRefinement(n),c=t._getHierarchicalFacetSeparator(i);if(s.length>0&&s[0].split(c).length>1){var u=s[0].split(c).slice(0,-1).reduce((function(e,t,r){return e.concat({attribute:i.attributes[r],value:0===r?t:[e[e.length-1].value,t].join(c)})}),[]);u.forEach((function(n,s){var c=a._getDisjunctiveFacetSearchParams(t,n.attribute,0===s);function o(e){return i.attributes.some((function(t){return t===e.split(":")[0]}))}var h=(c.facetFilters||[]).reduce((function(e,t){if(Array.isArray(t)){var r=t.filter((function(e){return!o(e)}));r.length>0&&e.push(r)}return"string"!=typeof t||o(t)||e.push(t),e}),[]),f=u[s-1];c.facetFilters=s>0?h.concat(f.attribute+":"+f.value):h.length>0?h:void 0,r.push({indexName:e,params:c})}))}})),r},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(a._getHitsHierarchicalFacetsAttributes(e)).sort(),r=a._getFacetFilters(e),s=a._getNumericFilters(e),c=a._getTagFilters(e),u={facets:t.indexOf("*")>-1?["*"]:t,tagFilters:c};return r.length>0&&(u.facetFilters=r),s.length>0&&(u.numericFilters=s),i(n({},e.getQueryParams(),u))},_getDisjunctiveFacetSearchParams:function(e,t,r){var s=a._getFacetFilters(e,t,r),c=a._getNumericFilters(e,t),u=a._getTagFilters(e),o={hitsPerPage:0,page:0,analytics:!1,clickAnalytics:!1};u.length>0&&(o.tagFilters=u);var h=e.getHierarchicalFacetByName(t);return o.facets=h?a._getDisjunctiveHierarchicalFacetAttribute(e,h,r):t,c.length>0&&(o.numericFilters=c),s.length>0&&(o.facetFilters=s),i(n({},e.getQueryParams(),o))},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var r=[];return Object.keys(e.numericRefinements).forEach((function(n){var i=e.numericRefinements[n]||{};Object.keys(i).forEach((function(e){var a=i[e]||[];t!==n&&a.forEach((function(t){if(Array.isArray(t)){var i=t.map((function(t){return n+e+t}));r.push(i)}else r.push(n+e+t)}))}))})),r},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,r){var n=[],i=e.facetsRefinements||{};Object.keys(i).sort().forEach((function(e){(i[e]||[]).sort().forEach((function(t){n.push(e+":"+t)}))}));var a=e.facetsExcludes||{};Object.keys(a).sort().forEach((function(e){(a[e]||[]).sort().forEach((function(t){n.push(e+":-"+t)}))}));var s=e.disjunctiveFacetsRefinements||{};Object.keys(s).sort().forEach((function(e){var r=s[e]||[];if(e!==t&&r&&0!==r.length){var i=[];r.sort().forEach((function(t){i.push(e+":"+t)})),n.push(i)}}));var c=e.hierarchicalFacetsRefinements||{};return Object.keys(c).sort().forEach((function(i){var a=(c[i]||[])[0];if(void 0!==a){var s,u,o=e.getHierarchicalFacetByName(i),h=e._getHierarchicalFacetSeparator(o),f=e._getHierarchicalRootPath(o);if(t===i){if(-1===a.indexOf(h)||!f&&!0===r||f&&f.split(h).length===a.split(h).length)return;f?(u=f.split(h).length-1,a=f):(u=a.split(h).length-2,a=a.slice(0,a.lastIndexOf(h))),s=o.attributes[u]}else u=a.split(h).length-1,s=o.attributes[u];s&&n.push([s+":"+a])}})),n},_getHitsHierarchicalFacetsAttributes:function(e){return e.hierarchicalFacets.reduce((function(t,r){var n=e.getHierarchicalRefinement(r.name)[0];if(!n)return t.push(r.attributes[0]),t;var i=e._getHierarchicalFacetSeparator(r),a=n.split(i).length,s=r.attributes.slice(0,a+1);return t.concat(s)}),[])},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,r){var n=e._getHierarchicalFacetSeparator(t);if(!0===r){var i=e._getHierarchicalRootPath(t),a=0;return i&&(a=i.split(n).length),[t.attributes[a]]}var s=(e.getHierarchicalRefinement(t.name)[0]||"").split(n).length-1;return t.attributes.slice(0,s+1)},getSearchForFacetQuery:function(e,t,r,s){var c=s.isDisjunctiveFacet(e)?s.clearRefinements(e):s,u={facetQuery:t,facetName:e};return"number"==typeof r&&(u.maxFacetHits=r),i(n({},a._getHitsSearchParams(c),u))}};e.exports=a},6801:e=>{"use strict";e.exports=function(e){return null!==e&&/^[a-zA-Z0-9_-]{1,64}$/.test(e)}},4336:e=>{"use strict";e.exports="3.16.1"},290:function(e){e.exports=function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var r=[],n=!0,i=!1,a=void 0;try{for(var s,c=e[Symbol.iterator]();!(n=(s=c.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{n||null==c.return||c.return()}finally{if(i)throw a}}return r}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function a(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){c();var t=JSON.stringify(e);return a()[t]})).then((function(e){return Promise.all([e?e.value:t(),void 0!==e])})).then((function(e){var t=i(e,2),n=t[0],a=t[1];return Promise.all([n,a||r.miss(n)])})).then((function(e){return i(e,1)[0]}))},set:function(e,t){return Promise.resolve().then((function(){var i=a();return i[JSON.stringify(e)]={timestamp:(new Date).getTime(),value:t},n().setItem(r,JSON.stringify(i)),t}))},delete:function(e){return Promise.resolve().then((function(){var t=a();delete t[JSON.stringify(e)],n().setItem(r,JSON.stringify(t))}))},clear:function(){return Promise.resolve().then((function(){n().removeItem(r)}))}}}function c(e){var t=a(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return t().then((function(e){return Promise.all([e,r.miss(e)])})).then((function(e){return i(e,1)[0]}))},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,i).catch((function(){return c({caches:t}).get(e,n,i)}))},set:function(e,n){return r.set(e,n).catch((function(){return c({caches:t}).set(e,n)}))},delete:function(e){return r.delete(e).catch((function(){return c({caches:t}).delete(e)}))},clear:function(){return r.clear().catch((function(){return c({caches:t}).clear()}))}}}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var s=n(),c=i&&i.miss||function(){return Promise.resolve()};return s.then((function(e){return c(e)})).then((function(){return s}))},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function o(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}function h(e,t){return t?(Object.keys(t).forEach((function(r){e[r]=t[r](e)})),e):e}function f(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var d={Read:1,Write:2,Any:3},p=1,v=2,g=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function R(e){return"string"==typeof e?{protocol:"https",url:e,accept:d.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||d.Any}}var F="GET",b="POST";function P(e,t){return Promise.all(t.map((function(t){return e.get(t,(function(){return Promise.resolve(y(t))}))}))).then((function(e){var r=e.filter((function(e){return function(e){return e.status===p||Date.now()-e.lastUpdate>12e4}(e)})),n=e.filter((function(e){return function(e){return e.status===g&&Date.now()-e.lastUpdate<=12e4}(e)})),i=[].concat(a(r),a(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:i.length>0?i.map((function(e){return R(e)})):t}}))}function j(e,t,n,i){var s=[],c=function(e,t){if(e.method!==F&&(void 0!==e.data||void 0!==t.data)){var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}}(n,i),u=function(e,t){var n=r(r({},e.headers),t.headers),i={};return Object.keys(n).forEach((function(e){var t=n[e];i[e.toLowerCase()]=t})),i}(e,i),o=n.method,h=n.method!==F?{}:r(r({},n.data),i.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),h),i.queryParameters),l=0,m=function t(r,a){var h=r.pop();if(void 0===h)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:O(s)};var m={data:c,headers:u,method:o,url:E(h,n.path,f),connectTimeout:a(l,e.timeouts.connect),responseTimeout:a(l,i.timeout)},d=function(e){var t={request:m,response:e,host:h,triesLeft:r.length};return s.push(t),t},p={onSuccess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var i=d(n);return n.isTimedOut&&l++,Promise.all([e.logger.info("Retryable failure",w(i)),e.hostsCache.set(h,y(h,n.isTimedOut?g:v))]).then((function(){return t(r,a)}))},onFail:function(e){throw d(e),function(e,t){var r=e.content,n=e.status,i=r;try{i=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}(i,n,t)}(e,O(s))}};return e.requester.send(m).then((function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSuccess(e):t.onFail(e)}(e,p)}))};return P(e.hostsCache,t).then((function(e){return m(a(e.statelessHosts).reverse(),e.getTimeout)}))}function _(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function E(e,t,r){var n=x(r),i="".concat(e.protocol,"://").concat(e.url,"/").concat("/"===t.charAt(0)?t.substr(1):t);return n.length&&(i+="?".concat(n)),i}function x(e){return Object.keys(e).map((function(t){return f("%s=%s",t,(r=e[t],"[object Object]"===Object.prototype.toString.call(r)||"[object Array]"===Object.prototype.toString.call(r)?JSON.stringify(e[t]):e[t]));var r})).join("&")}function O(e){return e.map((function(e){return w(e)}))}function w(e){var t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},e),{},{request:r(r({},e.request),{},{headers:r(r({},e.request.headers),t)})})}var N=function(e){var t=e.appId,n=function(e,t,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers:function(){return e===l.WithinHeaders?n:{}},queryParameters:function(){return e===l.WithinQueryParameters?n:{}}}}(void 0!==e.authMode?e.authMode:l.WithinHeaders,t,e.apiKey),a=function(e){var t=e.hostsCache,r=e.logger,n=e.requester,a=e.requestsCache,s=e.responsesCache,c=e.timeouts,u=e.userAgent,o=e.hosts,h=e.queryParameters,f={hostsCache:t,logger:r,requester:n,requestsCache:a,responsesCache:s,timeouts:c,userAgent:u,headers:e.headers,queryParameters:h,hosts:o.map((function(e){return R(e)})),read:function(e,t){var r=m(t,f.timeouts.read),n=function(){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Read)})),e,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:e.cacheable))return n();var a={request:e,mappedRequestOptions:r,transporter:{queryParameters:f.queryParameters,headers:f.headers}};return f.responsesCache.get(a,(function(){return f.requestsCache.get(a,(function(){return f.requestsCache.set(a,n()).then((function(e){return Promise.all([f.requestsCache.delete(a),e])}),(function(e){return Promise.all([f.requestsCache.delete(a),Promise.reject(e)])})).then((function(e){var t=i(e,2);return t[0],t[1]}))}))}),{miss:function(e){return f.responsesCache.set(a,e)}})},write:function(e,t){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Write)})),e,m(t,f.timeouts.write))}};return f}(r(r({hosts:[{url:"".concat(t,"-dsn.algolia.net"),accept:d.Read},{url:"".concat(t,".algolia.net"),accept:d.Write}].concat(o([{url:"".concat(t,"-1.algolianet.com")},{url:"".concat(t,"-2.algolianet.com")},{url:"".concat(t,"-3.algolianet.com")}]))},e),{},{headers:r(r(r({},n.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:r(r({},n.queryParameters()),e.queryParameters)}));return h({transporter:a,appId:t,addAlgoliaAgent:function(e,t){a.userAgent.add({segment:e,version:t})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then((function(){}))}},e.methods)},A=function(e){return function(t,r){return t.method===F?e.transporter.read(t,r):e.transporter.write(t,r)}},H=function(e){return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return h({transporter:e.transporter,appId:e.appId,indexName:t},r.methods)}},S=function(e){return function(t,n){var i=t.map((function(e){return r(r({},e),{},{params:x(e.params||{})})}));return e.transporter.read({method:b,path:"1/indexes/*/queries",data:{requests:i},cacheable:!0},n)}},T=function(e){return function(t,i){return Promise.all(t.map((function(t){var a=t.params,s=a.facetName,c=a.facetQuery,u=n(a,["facetName","facetQuery"]);return H(e)(t.indexName,{methods:{searchForFacetValues:I}}).searchForFacetValues(s,c,r(r({},i),u))})))}},Q=function(e){return function(t,r,n){return e.transporter.read({method:b,path:f("1/answers/%s/prediction",e.indexName),data:{query:t,queryLanguages:r},cacheable:!0},n)}},C=function(e){return function(t,r){return e.transporter.read({method:b,path:f("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r)}},I=function(e){return function(t,r,n){return e.transporter.read({method:b,path:f("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},n)}},k=1,D=2,q=3;function V(e,t,n){var i,a={appId:e,apiKey:t,timeouts:{connect:1,read:2,write:30},requester:{send:function(e){return new Promise((function(t){var r=new XMLHttpRequest;r.open(e.method,e.url,!0),Object.keys(e.headers).forEach((function(t){return r.setRequestHeader(t,e.headers[t])}));var n,i=function(e,n){return setTimeout((function(){r.abort(),t({status:0,content:n,isTimedOut:!0})}),1e3*e)},a=i(e.connectTimeout,"Connection timeout");r.onreadystatechange=function(){r.readyState>r.OPENED&&void 0===n&&(clearTimeout(a),n=i(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)}))}},logger:(i=q,{debug:function(e,t){return k>=i&&console.debug(e,t),Promise.resolve()},info:function(e,t){return D>=i&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:u(),requestsCache:u({serializable:!1}),hostsCache:c({caches:[s({key:"".concat("4.22.1","-").concat(e)}),u()]}),userAgent:_("4.22.1").add({segment:"Browser",version:"lite"}),authMode:l.WithinQueryParameters};return N(r(r(r({},a),n),{},{methods:{search:S,searchForFacetValues:T,multipleQueries:S,multipleSearchForFacetValues:T,customRequest:A,initIndex:function(e){return function(t){return H(e)(t,{methods:{search:C,searchForFacetValues:I,findAnswers:Q}})}}}}))}return V.version="4.22.1",V}()},6675:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>A});var n=r(7294),i=r(6010),a=r(8131),s=r.n(a),c=r(290),u=r.n(c),o=r(412),h=r(5742),f=r(9960),l=r(143),m=r(2263);const d=["zero","one","two","few","many","other"];function p(e){return d.filter((t=>e.includes(t)))}const v={locale:"en",pluralForms:p(["one","other"]),select:e=>1===e?"one":"other"};function g(){const{i18n:{currentLocale:e}}=(0,m.Z)();return(0,n.useMemo)((()=>{try{return function(e){const t=new Intl.PluralRules(e);return{locale:e,pluralForms:p(t.resolvedOptions().pluralCategories),select:e=>t.select(e)}}(e)}catch(t){return console.error(`Failed to use Intl.PluralRules for locale "${e}".\nDocusaurus will fallback to the default (English) implementation.\nError: ${t.message}\n`),v}}),[e])}function y(){const e=g();return{selectMessage:(t,r)=>function(e,t,r){const n=e.split("|");if(1===n.length)return n[0];n.length>r.pluralForms.length&&console.error(`For locale=${r.locale}, a maximum of ${r.pluralForms.length} plural forms are expected (${r.pluralForms.join(",")}), but the message contains ${n.length}: ${e}`);const i=r.select(t),a=r.pluralForms.indexOf(i);return n[Math.min(a,n.length-1)]}(r,t,e)}}var R=r(6177),F=r(902),b=r(833),P=r(2128),j=r(5999),_=r(6278),E=r(239),x=r(7452);const O={searchQueryInput:"searchQueryInput_u2C7",searchVersionInput:"searchVersionInput_m0Ui",searchResultsColumn:"searchResultsColumn_JPFH",algoliaLogo:"algoliaLogo_rT1R",algoliaLogoPathFill:"algoliaLogoPathFill_WdUC",searchResultItem:"searchResultItem_Tv2o",searchResultItemHeading:"searchResultItemHeading_KbCB",searchResultItemPath:"searchResultItemPath_lhe1",searchResultItemSummary:"searchResultItemSummary_AEaO",searchQueryColumn:"searchQueryColumn_RTkw",searchVersionColumn:"searchVersionColumn_ypXd",searchLogoColumn:"searchLogoColumn_rJIA",loadingSpinner:"loadingSpinner_XVxU","loading-spin":"loading-spin_vzvp",loader:"loader_vvXV"};function w(e){let{docsSearchVersionsHelpers:t}=e;const r=Object.entries(t.allDocsData).filter((e=>{let[,t]=e;return t.versions.length>1}));return n.createElement("div",{className:(0,i.Z)("col","col--3","padding-left--none",O.searchVersionColumn)},r.map((e=>{let[i,a]=e;const s=r.length>1?`${i}: `:"";return n.createElement("select",{key:i,onChange:e=>t.setSearchVersion(i,e.target.value),defaultValue:t.searchVersions[i],className:O.searchVersionInput},a.versions.map(((e,t)=>n.createElement("option",{key:t,label:`${s}${e.label}`,value:e.name}))))})))}function N(){const{i18n:{currentLocale:e}}=(0,m.Z)(),{algolia:{appId:t,apiKey:r,indexName:a}}=(0,_.L)(),c=(0,E.l)(),d=function(){const{selectMessage:e}=y();return t=>e(t,(0,j.I)({id:"theme.SearchPage.documentsFound.plurals",description:'Pluralized label for "{count} documents found". Use as much plural forms (separated by "|") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)',message:"One document found|{count} documents found"},{count:t}))}(),p=function(){const e=(0,l._r)(),[t,r]=(0,n.useState)((()=>Object.entries(e).reduce(((e,t)=>{let[r,n]=t;return{...e,[r]:n.versions[0].name}}),{}))),i=Object.values(e).some((e=>e.versions.length>1));return{allDocsData:e,versioningEnabled:i,searchVersions:t,setSearchVersion:(e,t)=>r((r=>({...r,[e]:t})))}}(),[v,g]=(0,R.K)(),b={items:[],query:null,totalResults:null,totalPages:null,lastPage:null,hasMore:null,loading:null},[N,A]=(0,n.useReducer)(((e,t)=>{switch(t.type){case"reset":return b;case"loading":return{...e,loading:!0};case"update":return v!==t.value.query?e:{...t.value,items:0===t.value.lastPage?t.value.items:e.items.concat(t.value.items)};case"advance":{const t=e.totalPages>e.lastPage+1;return{...e,lastPage:t?e.lastPage+1:e.lastPage,hasMore:t}}default:return e}}),b),H=u()(t,r),S=s()(H,a,{hitsPerPage:15,advancedSyntax:!0,disjunctiveFacets:["language","docusaurus_tag"]});S.on("result",(e=>{let{results:{query:t,hits:r,page:n,nbHits:i,nbPages:a}}=e;if(""===t||!Array.isArray(r))return void A({type:"reset"});const s=e=>e.replace(/algolia-docsearch-suggestion--highlight/g,"search-result-match"),u=r.map((e=>{let{url:t,_highlightResult:{hierarchy:r},_snippetResult:n={}}=e;const i=Object.keys(r).map((e=>s(r[e].value)));return{title:i.pop(),url:c(t),summary:n.content?`${s(n.content.value)}...`:"",breadcrumbs:i}}));A({type:"update",value:{items:u,query:t,totalResults:i,totalPages:a,lastPage:n,hasMore:a>n+1,loading:!1}})}));const[T,Q]=(0,n.useState)(null),C=(0,n.useRef)(0),I=(0,n.useRef)(o.Z.canUseIntersectionObserver&&new IntersectionObserver((e=>{const{isIntersecting:t,boundingClientRect:{y:r}}=e[0];t&&C.current>r&&A({type:"advance"}),C.current=r}),{threshold:1})),k=()=>v?(0,j.I)({id:"theme.SearchPage.existingResultsTitle",message:'Search results for "{query}"',description:"The search page title for non-empty query"},{query:v}):(0,j.I)({id:"theme.SearchPage.emptyResultsTitle",message:"Search the documentation",description:"The search page title for empty query"}),D=(0,F.zX)((function(t){void 0===t&&(t=0),S.addDisjunctiveFacetRefinement("docusaurus_tag","default"),S.addDisjunctiveFacetRefinement("language",e),Object.entries(p.searchVersions).forEach((e=>{let[t,r]=e;S.addDisjunctiveFacetRefinement("docusaurus_tag",`docs-${t}-${r}`)})),S.setQuery(v).setPage(t).search()}));return(0,n.useEffect)((()=>{if(!T)return;const e=I.current;return e?(e.observe(T),()=>e.unobserve(T)):()=>!0}),[T]),(0,n.useEffect)((()=>{A({type:"reset"}),v&&(A({type:"loading"}),setTimeout((()=>{D()}),300))}),[v,p.searchVersions,D]),(0,n.useEffect)((()=>{N.lastPage&&0!==N.lastPage&&D(N.lastPage)}),[D,N.lastPage]),n.createElement(x.Z,null,n.createElement(h.Z,null,n.createElement("title",null,(0,P.p)(k())),n.createElement("meta",{property:"robots",content:"noindex, follow"})),n.createElement("div",{className:"container margin-vert--lg"},n.createElement("h1",null,k()),n.createElement("form",{className:"row",onSubmit:e=>e.preventDefault()},n.createElement("div",{className:(0,i.Z)("col",O.searchQueryColumn,{"col--9":p.versioningEnabled,"col--12":!p.versioningEnabled})},n.createElement("input",{type:"search",name:"q",className:O.searchQueryInput,placeholder:(0,j.I)({id:"theme.SearchPage.inputPlaceholder",message:"Type your search here",description:"The placeholder for search page input"}),"aria-label":(0,j.I)({id:"theme.SearchPage.inputLabel",message:"Search",description:"The ARIA label for search page input"}),onChange:e=>g(e.target.value),value:v,autoComplete:"off",autoFocus:!0})),p.versioningEnabled&&n.createElement(w,{docsSearchVersionsHelpers:p})),n.createElement("div",{className:"row"},n.createElement("div",{className:(0,i.Z)("col","col--8",O.searchResultsColumn)},!!N.totalResults&&d(N.totalResults)),n.createElement("div",{className:(0,i.Z)("col","col--4","text--right",O.searchLogoColumn)},n.createElement("a",{target:"_blank",rel:"noopener noreferrer",href:"https://www.algolia.com/","aria-label":(0,j.I)({id:"theme.SearchPage.algoliaLabel",message:"Search by Algolia",description:"The ARIA label for Algolia mention"})},n.createElement("svg",{viewBox:"0 0 168 24",className:O.algoliaLogo},n.createElement("g",{fill:"none"},n.createElement("path",{className:O.algoliaLogoPathFill,d:"M120.925 18.804c-4.386.02-4.386-3.54-4.386-4.106l-.007-13.336 2.675-.424v13.254c0 .322 0 2.358 1.718 2.364v2.248zm-10.846-2.18c.821 0 1.43-.047 1.855-.129v-2.719a6.334 6.334 0 0 0-1.574-.199 5.7 5.7 0 0 0-.897.069 2.699 2.699 0 0 0-.814.24c-.24.116-.439.28-.582.491-.15.212-.219.335-.219.656 0 .628.219.991.616 1.23s.938.362 1.615.362zm-.233-9.7c.883 0 1.629.109 2.231.328.602.218 1.088.525 1.444.915.363.396.609.922.76 1.483.157.56.232 1.175.232 1.85v6.874a32.5 32.5 0 0 1-1.868.314c-.834.123-1.772.185-2.813.185-.69 0-1.327-.069-1.895-.198a4.001 4.001 0 0 1-1.471-.636 3.085 3.085 0 0 1-.951-1.134c-.226-.465-.343-1.12-.343-1.803 0-.656.13-1.073.384-1.525a3.24 3.24 0 0 1 1.047-1.106c.445-.287.95-.492 1.532-.615a8.8 8.8 0 0 1 1.82-.185 8.404 8.404 0 0 1 1.972.24v-.438c0-.307-.035-.6-.11-.874a1.88 1.88 0 0 0-.384-.73 1.784 1.784 0 0 0-.724-.493 3.164 3.164 0 0 0-1.143-.205c-.616 0-1.177.075-1.69.164a7.735 7.735 0 0 0-1.26.307l-.321-2.192c.335-.117.834-.233 1.478-.349a10.98 10.98 0 0 1 2.073-.178zm52.842 9.626c.822 0 1.43-.048 1.854-.13V13.7a6.347 6.347 0 0 0-1.574-.199c-.294 0-.595.021-.896.069a2.7 2.7 0 0 0-.814.24 1.46 1.46 0 0 0-.582.491c-.15.212-.218.335-.218.656 0 .628.218.991.615 1.23.404.245.938.362 1.615.362zm-.226-9.694c.883 0 1.629.108 2.231.327.602.219 1.088.526 1.444.915.355.39.609.923.759 1.483a6.8 6.8 0 0 1 .233 1.852v6.873c-.41.088-1.034.19-1.868.314-.834.123-1.772.184-2.813.184-.69 0-1.327-.068-1.895-.198a4.001 4.001 0 0 1-1.471-.635 3.085 3.085 0 0 1-.951-1.134c-.226-.465-.343-1.12-.343-1.804 0-.656.13-1.073.384-1.524.26-.45.608-.82 1.047-1.107.445-.286.95-.491 1.532-.614a8.803 8.803 0 0 1 2.751-.13c.329.034.671.096 1.04.185v-.437a3.3 3.3 0 0 0-.109-.875 1.873 1.873 0 0 0-.384-.731 1.784 1.784 0 0 0-.724-.492 3.165 3.165 0 0 0-1.143-.205c-.616 0-1.177.075-1.69.164a7.75 7.75 0 0 0-1.26.307l-.321-2.193c.335-.116.834-.232 1.478-.348a11.633 11.633 0 0 1 2.073-.177zm-8.034-1.271a1.626 1.626 0 0 1-1.628-1.62c0-.895.725-1.62 1.628-1.62.904 0 1.63.725 1.63 1.62 0 .895-.733 1.62-1.63 1.62zm1.348 13.22h-2.689V7.27l2.69-.423v11.956zm-4.714 0c-4.386.02-4.386-3.54-4.386-4.107l-.008-13.336 2.676-.424v13.254c0 .322 0 2.358 1.718 2.364v2.248zm-8.698-5.903c0-1.156-.253-2.119-.746-2.788-.493-.677-1.183-1.01-2.067-1.01-.882 0-1.574.333-2.065 1.01-.493.676-.733 1.632-.733 2.788 0 1.168.246 1.953.74 2.63.492.683 1.183 1.018 2.066 1.018.882 0 1.574-.342 2.067-1.019.492-.683.738-1.46.738-2.63zm2.737-.007c0 .902-.13 1.584-.397 2.33a5.52 5.52 0 0 1-1.128 1.906 4.986 4.986 0 0 1-1.752 1.223c-.685.286-1.739.45-2.265.45-.528-.006-1.574-.157-2.252-.45a5.096 5.096 0 0 1-1.744-1.223c-.487-.527-.863-1.162-1.137-1.906a6.345 6.345 0 0 1-.41-2.33c0-.902.123-1.77.397-2.508a5.554 5.554 0 0 1 1.15-1.892 5.133 5.133 0 0 1 1.75-1.216c.679-.287 1.425-.423 2.232-.423.808 0 1.553.142 2.237.423a4.88 4.88 0 0 1 1.753 1.216 5.644 5.644 0 0 1 1.135 1.892c.287.738.431 1.606.431 2.508zm-20.138 0c0 1.12.246 2.363.738 2.882.493.52 1.13.78 1.91.78.424 0 .828-.062 1.204-.178.377-.116.677-.253.917-.417V9.33a10.476 10.476 0 0 0-1.766-.226c-.971-.028-1.71.37-2.23 1.004-.513.636-.773 1.75-.773 2.788zm7.438 5.274c0 1.824-.466 3.156-1.404 4.004-.936.846-2.367 1.27-4.296 1.27-.705 0-2.17-.137-3.34-.396l.431-2.118c.98.205 2.272.26 2.95.26 1.074 0 1.84-.219 2.299-.656.459-.437.684-1.086.684-1.948v-.437a8.07 8.07 0 0 1-1.047.397c-.43.13-.93.198-1.492.198-.739 0-1.41-.116-2.018-.349a4.206 4.206 0 0 1-1.567-1.025c-.431-.45-.774-1.017-1.013-1.694-.24-.677-.363-1.885-.363-2.773 0-.834.13-1.88.384-2.577.26-.696.629-1.298 1.129-1.796.493-.498 1.095-.881 1.8-1.162a6.605 6.605 0 0 1 2.428-.457c.87 0 1.67.109 2.45.24.78.129 1.444.265 1.985.415V18.17zM6.972 6.677v1.627c-.712-.446-1.52-.67-2.425-.67-.585 0-1.045.13-1.38.391a1.24 1.24 0 0 0-.502 1.03c0 .425.164.765.494 1.02.33.256.835.532 1.516.83.447.192.795.356 1.045.495.25.138.537.332.862.582.324.25.563.548.718.894.154.345.23.741.23 1.188 0 .947-.334 1.691-1.004 2.234-.67.542-1.537.814-2.601.814-1.18 0-2.16-.229-2.936-.686v-1.708c.84.628 1.814.942 2.92.942.585 0 1.048-.136 1.388-.407.34-.271.51-.646.51-1.125 0-.287-.1-.55-.302-.79-.203-.24-.42-.42-.655-.542-.234-.123-.585-.29-1.053-.503a61.27 61.27 0 0 1-.582-.271 13.67 13.67 0 0 1-.55-.287 4.275 4.275 0 0 1-.567-.351 6.92 6.92 0 0 1-.455-.4c-.18-.17-.31-.34-.39-.51-.08-.17-.155-.37-.224-.598a2.553 2.553 0 0 1-.104-.742c0-.915.333-1.638.998-2.17.664-.532 1.523-.798 2.576-.798.968 0 1.793.17 2.473.51zm7.468 5.696v-.287c-.022-.607-.187-1.088-.495-1.444-.309-.357-.75-.535-1.324-.535-.532 0-.99.194-1.373.583-.382.388-.622.949-.717 1.683h3.909zm1.005 2.792v1.404c-.596.34-1.383.51-2.362.51-1.255 0-2.255-.377-3-1.132-.744-.755-1.116-1.744-1.116-2.968 0-1.297.34-2.316 1.021-3.055.68-.74 1.548-1.11 2.6-1.11 1.033 0 1.852.323 2.458.966.606.644.91 1.572.91 2.784 0 .33-.033.676-.096 1.038h-5.314c.107.702.405 1.239.894 1.611.49.372 1.106.558 1.85.558.862 0 1.58-.202 2.155-.606zm6.605-1.77h-1.212c-.596 0-1.045.116-1.349.35-.303.234-.454.532-.454.894 0 .372.117.664.35.877.235.213.575.32 1.022.32.51 0 .912-.142 1.204-.424.293-.281.44-.651.44-1.108v-.91zm-4.068-2.554V9.325c.627-.361 1.457-.542 2.489-.542 2.116 0 3.175 1.026 3.175 3.08V17h-1.548v-.957c-.415.68-1.143 1.02-2.186 1.02-.766 0-1.38-.22-1.843-.661-.462-.442-.694-1.003-.694-1.684 0-.776.293-1.38.878-1.81.585-.431 1.404-.647 2.457-.647h1.34V11.8c0-.554-.133-.971-.399-1.253-.266-.282-.707-.423-1.324-.423a4.07 4.07 0 0 0-2.345.718zm9.333-1.93v1.42c.394-1 1.101-1.5 2.123-1.5.148 0 .313.016.494.048v1.531a1.885 1.885 0 0 0-.75-.143c-.542 0-.989.24-1.34.718-.351.479-.527 1.048-.527 1.707V17h-1.563V8.91h1.563zm5.01 4.084c.022.82.272 1.492.75 2.019.479.526 1.15.79 2.01.79.639 0 1.235-.176 1.788-.527v1.404c-.521.319-1.186.479-1.995.479-1.265 0-2.276-.4-3.031-1.197-.755-.798-1.133-1.792-1.133-2.984 0-1.16.38-2.151 1.14-2.975.761-.825 1.79-1.237 3.088-1.237.702 0 1.346.149 1.93.447v1.436a3.242 3.242 0 0 0-1.77-.495c-.84 0-1.513.266-2.019.798-.505.532-.758 1.213-.758 2.042zM40.24 5.72v4.579c.458-1 1.293-1.5 2.505-1.5.787 0 1.42.245 1.899.734.479.49.718 1.17.718 2.042V17h-1.564v-5.106c0-.553-.14-.98-.422-1.284-.282-.303-.652-.455-1.11-.455-.531 0-1.002.202-1.411.606-.41.405-.615 1.022-.615 1.851V17h-1.563V5.72h1.563zm14.966 10.02c.596 0 1.096-.253 1.5-.758.404-.506.606-1.157.606-1.955 0-.915-.202-1.62-.606-2.114-.404-.495-.92-.742-1.548-.742-.553 0-1.05.224-1.491.67-.442.447-.662 1.133-.662 2.058 0 .958.212 1.67.638 2.138.425.469.946.703 1.563.703zM53.004 5.72v4.42c.574-.894 1.388-1.341 2.44-1.341 1.022 0 1.857.383 2.506 1.149.649.766.973 1.781.973 3.047 0 1.138-.309 2.109-.925 2.912-.617.803-1.463 1.205-2.537 1.205-1.075 0-1.894-.447-2.457-1.34V17h-1.58V5.72h1.58zm9.908 11.104l-3.223-7.913h1.739l1.005 2.632 1.26 3.415c.096-.32.48-1.458 1.15-3.415l.909-2.632h1.66l-2.92 7.866c-.777 2.074-1.963 3.11-3.559 3.11a2.92 2.92 0 0 1-.734-.079v-1.34c.17.042.351.064.543.064 1.032 0 1.755-.57 2.17-1.708z"}),n.createElement("path",{fill:"#5468FF",d:"M78.988.938h16.594a2.968 2.968 0 0 1 2.966 2.966V20.5a2.967 2.967 0 0 1-2.966 2.964H78.988a2.967 2.967 0 0 1-2.966-2.964V3.897A2.961 2.961 0 0 1 78.988.938z"}),n.createElement("path",{fill:"white",d:"M89.632 5.967v-.772a.978.978 0 0 0-.978-.977h-2.28a.978.978 0 0 0-.978.977v.793c0 .088.082.15.171.13a7.127 7.127 0 0 1 1.984-.28c.65 0 1.295.088 1.917.259.082.02.164-.04.164-.13m-6.248 1.01l-.39-.389a.977.977 0 0 0-1.382 0l-.465.465a.973.973 0 0 0 0 1.38l.383.383c.062.061.15.047.205-.014.226-.307.472-.601.746-.874.281-.28.568-.526.883-.751.068-.042.075-.137.02-.2m4.16 2.453v3.341c0 .096.104.165.192.117l2.97-1.537c.068-.034.089-.117.055-.184a3.695 3.695 0 0 0-3.08-1.866c-.068 0-.136.054-.136.13m0 8.048a4.489 4.489 0 0 1-4.49-4.482 4.488 4.488 0 0 1 4.49-4.482 4.488 4.488 0 0 1 4.489 4.482 4.484 4.484 0 0 1-4.49 4.482m0-10.85a6.363 6.363 0 1 0 0 12.729 6.37 6.37 0 0 0 6.372-6.368 6.358 6.358 0 0 0-6.371-6.36"})))))),N.items.length>0?n.createElement("main",null,N.items.map(((e,t)=>{let{title:r,url:a,summary:s,breadcrumbs:c}=e;return n.createElement("article",{key:t,className:O.searchResultItem},n.createElement("h2",{className:O.searchResultItemHeading},n.createElement(f.Z,{to:a,dangerouslySetInnerHTML:{__html:r}})),c.length>0&&n.createElement("nav",{"aria-label":"breadcrumbs"},n.createElement("ul",{className:(0,i.Z)("breadcrumbs",O.searchResultItemPath)},c.map(((e,t)=>n.createElement("li",{key:t,className:"breadcrumbs__item",dangerouslySetInnerHTML:{__html:e}}))))),s&&n.createElement("p",{className:O.searchResultItemSummary,dangerouslySetInnerHTML:{__html:s}}))}))):[v&&!N.loading&&n.createElement("p",{key:"no-results"},n.createElement(j.Z,{id:"theme.SearchPage.noResultsText",description:"The paragraph for empty search result"},"No results were found")),!!N.loading&&n.createElement("div",{key:"spinner",className:O.loadingSpinner})],N.hasMore&&n.createElement("div",{className:O.loader,ref:Q},n.createElement(j.Z,{id:"theme.SearchPage.fetchingNewResults",description:"The paragraph for fetching new search results"},"Fetching new results..."))))}function A(){return n.createElement(b.FG,{className:"search-page-wrapper"},n.createElement(N,null))}}}]); \ No newline at end of file diff --git a/assets/js/1aa05129.97a1b6e7.js b/assets/js/1aa05129.bd36efa9.js similarity index 98% rename from assets/js/1aa05129.97a1b6e7.js rename to assets/js/1aa05129.bd36efa9.js index 647728fc5c..fb56ab0278 100644 --- a/assets/js/1aa05129.97a1b6e7.js +++ b/assets/js/1aa05129.bd36efa9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7178],{3391:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-6.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-6.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/6.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/implementing-security.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/6.0/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7178],{3391:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-6.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-6.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/6.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/implementing-security.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/6.0/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1b1927f4.f12b39fa.js b/assets/js/1b1927f4.573f9cb0.js similarity index 97% rename from assets/js/1b1927f4.f12b39fa.js rename to assets/js/1b1927f4.573f9cb0.js index 76328ac43f..8ef7ec14ab 100644 --- a/assets/js/1b1927f4.f12b39fa.js +++ b/assets/js/1b1927f4.573f9cb0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2946],{4277:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},p=void 0,o={unversionedId:"multiple-output-types",id:"version-6.1/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/multiple-output-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/symfony-bundle-advanced"}},s={},u=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:u},r="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(r,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,i.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("h2",{id:"example"},"Example"),(0,i.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.kt)("a",{parentName:"p",href:"/docs/external-type-declaration"},'"external" type')," mapping the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("p",null,"First of all, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,i.kt)("p",null,"Then, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.kt)("p",null,"Finally, we can write our requests:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n')),(0,i.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.kt)("p",null,"Is a result, when the end user calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.kt)("p",null,"If you want to extend a type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.kt)("p",null,"So instead of writing:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.kt)("p",null,"you will write:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2946],{4277:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},p=void 0,o={unversionedId:"multiple-output-types",id:"version-6.1/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/multiple-output-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/symfony-bundle-advanced"}},s={},u=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:u},r="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(r,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,i.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("h2",{id:"example"},"Example"),(0,i.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.kt)("a",{parentName:"p",href:"/docs/external-type-declaration"},'"external" type')," mapping the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("p",null,"First of all, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,i.kt)("p",null,"Then, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.kt)("p",null,"Finally, we can write our requests:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n')),(0,i.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.kt)("p",null,"Is a result, when the end user calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.kt)("p",null,"If you want to extend a type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.kt)("p",null,"So instead of writing:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.kt)("p",null,"you will write:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1ba75d10.a69e3319.js b/assets/js/1ba75d10.3f051919.js similarity index 99% rename from assets/js/1ba75d10.a69e3319.js rename to assets/js/1ba75d10.3f051919.js index f65f9f8e4a..85e71feeb7 100644 --- a/assets/js/1ba75d10.a69e3319.js +++ b/assets/js/1ba75d10.3f051919.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[186],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},8104:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.2/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.2/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.2/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/mutations.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-4.2/docs",previous:{title:"Queries",permalink:"/docs/4.2/queries"},next:{title:"Type mapping",permalink:"/docs/4.2/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[186],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},8104:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.2/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.2/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.2/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/mutations.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-4.2/docs",previous:{title:"Queries",permalink:"/docs/4.2/queries"},next:{title:"Type mapping",permalink:"/docs/4.2/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1d703573.7c629ab0.js b/assets/js/1d703573.a109bf96.js similarity index 94% rename from assets/js/1d703573.7c629ab0.js rename to assets/js/1d703573.a109bf96.js index 93d4cacfbf..01488b8d6c 100644 --- a/assets/js/1d703573.7c629ab0.js +++ b/assets/js/1d703573.a109bf96.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4735],{3416:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.2/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.2/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.2/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/getting-started.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.2/docs",previous:{title:"GraphQLite",permalink:"/docs/4.2/"},next:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4735],{3416:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.2/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.2/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.2/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/getting-started.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.2/docs",previous:{title:"GraphQLite",permalink:"/docs/4.2/"},next:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1e2c5f46.360bac5c.js b/assets/js/1e2c5f46.a2a9a199.js similarity index 97% rename from assets/js/1e2c5f46.360bac5c.js rename to assets/js/1e2c5f46.a2a9a199.js index 991dfc42cd..6ba04b0f4b 100644 --- a/assets/js/1e2c5f46.360bac5c.js +++ b/assets/js/1e2c5f46.a2a9a199.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7794],{3671:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-6.1/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-6.1/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/semver.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^6"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~6.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7794],{3671:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-6.1/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-6.1/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/semver.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^6"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~6.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1e6ec01e.0a3b2b97.js b/assets/js/1e6ec01e.42b2995e.js similarity index 98% rename from assets/js/1e6ec01e.0a3b2b97.js rename to assets/js/1e6ec01e.42b2995e.js index f02ce8715d..49852800c4 100644 --- a/assets/js/1e6ec01e.0a3b2b97.js +++ b/assets/js/1e6ec01e.42b2995e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2923],{5934:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/docs/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/next/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/laravel-package.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/next/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/next/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},u="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2923],{5934:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/docs/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/next/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/laravel-package.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/next/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/next/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},u="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1e7fe27e.182e7367.js b/assets/js/1e7fe27e.76635a46.js similarity index 99% rename from assets/js/1e7fe27e.182e7367.js rename to assets/js/1e7fe27e.76635a46.js index caf317730e..3405ead155 100644 --- a/assets/js/1e7fe27e.182e7367.js +++ b/assets/js/1e7fe27e.76635a46.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3239],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6475:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-5.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-5.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/5.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/autowiring.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-5.0/docs",previous:{title:"Type mapping",permalink:"/docs/5.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/5.0/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3239],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6475:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-5.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-5.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/5.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/autowiring.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-5.0/docs",previous:{title:"Type mapping",permalink:"/docs/5.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/5.0/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1ea13486.0b572550.js b/assets/js/1ea13486.75b19a56.js similarity index 97% rename from assets/js/1ea13486.0b572550.js rename to assets/js/1ea13486.75b19a56.js index faa74aa0cb..2c9f54b535 100644 --- a/assets/js/1ea13486.0b572550.js +++ b/assets/js/1ea13486.75b19a56.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7967],{9312:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(7462),s=(r(7294),r(3905)),a=r(1839);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/docs/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/next/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/automatic-persisted-queries.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/next/prefetch-method"},next:{title:"File uploads",permalink:"/docs/next/file-uploads"}},l={},d=[{value:"The problem",id:"the-problem",level:2},{value:"Apollo APQ",id:"apollo-apq",level:2},{value:"Setup",id:"setup",level:2}],p={toc:d},c="wrapper";function h(e){let{components:t,...r}=e;return(0,s.kt)(c,(0,i.Z)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.kt)("h2",{id:"the-problem"},"The problem"),(0,s.kt)("p",null,"Clients send queries to GraphQLite as HTTP requests that include the GraphQL string of the query to execute.\nDepending on your graph's schema, the size of a valid query string might be arbitrarily large.\nAs query strings become larger, increased latency and network usage can noticeably degrade client performance."),(0,s.kt)("p",null,'To combat this, GraphQL servers use a technique called "persisted queries". The basic idea is instead of\nsending the whole query string, clients only send it\'s unique identifier. The server then finds the actual\nquery string by given identifier and use that as if the client sent the whole query in the first place.\nThat helps improve GraphQL network performance with zero build-time configuration by sending smaller GraphQL HTTP requests.\nA smaller request payload reduces bandwidth utilization and speeds up GraphQL Client loading times.'),(0,s.kt)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.kt)("p",null,(0,s.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/apollo-server/performance/apq/"},"Automatic persisted queries (APQ) is technique created by Apollo"),"\nand is aimed to implement a simple automatic way of persisting queries. Queries are cached on the server side,\nalong with its unique identifier (always its SHA-256 hash). Clients can send this identifier instead of the\ncorresponding query string, thus reducing request sizes dramatically (response sizes are unaffected)."),(0,s.kt)("p",null,"To persist a query string, GraphQLite server must first receive it from a requesting client.\nConsequently, each unique query string must be sent to Apollo Server at least once.\nAfter any client sends a query string to persist, every client that executes that query can then benefit from APQ."),(0,s.kt)(a.G,{chart:"sequenceDiagram;\n Client app->>GraphQL Server: Sends SHA-256 hash of query string to execute\n Note over GraphQL Server: Fails to find persisted query string\n GraphQL Server->>Client app: Responds with error\n Client app->>GraphQL Server: Sends both query string AND hash\n Note over GraphQL Server: Persists query string and hash\n GraphQL Server->>Client app: Executes query and returns result\n Note over Client app: Time passes\n Client app->>GraphQL Server: Sends SHA-256 hash of query string to execute\n Note over GraphQL Server: Finds persisted query string\n GraphQL Server->>Client app: Executes query and returns result",mdxType:"Mermaid"}),(0,s.kt)("p",null,"Persisted queries are especially effective when clients send queries as GET requests.\nThis enables clients to take advantage of the browser cache and integrate with a CDN."),(0,s.kt)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.kt)("h2",{id:"setup"},"Setup"),(0,s.kt)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.kt)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n// You need to provide a PSR compatible cache and a TTL for queries. The best cache would be some kind\n// of in-memory cache with a limit on number of entries to make sure your cache can't be maliciously spammed with queries.\n$builder->useAutomaticPersistedQueries($cache, new DateInterval('PT1H'));\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7967],{9312:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(7462),s=(r(7294),r(3905)),a=r(1839);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/docs/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/next/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/automatic-persisted-queries.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/next/prefetch-method"},next:{title:"File uploads",permalink:"/docs/next/file-uploads"}},l={},d=[{value:"The problem",id:"the-problem",level:2},{value:"Apollo APQ",id:"apollo-apq",level:2},{value:"Setup",id:"setup",level:2}],p={toc:d},c="wrapper";function h(e){let{components:t,...r}=e;return(0,s.kt)(c,(0,i.Z)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.kt)("h2",{id:"the-problem"},"The problem"),(0,s.kt)("p",null,"Clients send queries to GraphQLite as HTTP requests that include the GraphQL string of the query to execute.\nDepending on your graph's schema, the size of a valid query string might be arbitrarily large.\nAs query strings become larger, increased latency and network usage can noticeably degrade client performance."),(0,s.kt)("p",null,'To combat this, GraphQL servers use a technique called "persisted queries". The basic idea is instead of\nsending the whole query string, clients only send it\'s unique identifier. The server then finds the actual\nquery string by given identifier and use that as if the client sent the whole query in the first place.\nThat helps improve GraphQL network performance with zero build-time configuration by sending smaller GraphQL HTTP requests.\nA smaller request payload reduces bandwidth utilization and speeds up GraphQL Client loading times.'),(0,s.kt)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.kt)("p",null,(0,s.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/apollo-server/performance/apq/"},"Automatic persisted queries (APQ) is technique created by Apollo"),"\nand is aimed to implement a simple automatic way of persisting queries. Queries are cached on the server side,\nalong with its unique identifier (always its SHA-256 hash). Clients can send this identifier instead of the\ncorresponding query string, thus reducing request sizes dramatically (response sizes are unaffected)."),(0,s.kt)("p",null,"To persist a query string, GraphQLite server must first receive it from a requesting client.\nConsequently, each unique query string must be sent to Apollo Server at least once.\nAfter any client sends a query string to persist, every client that executes that query can then benefit from APQ."),(0,s.kt)(a.G,{chart:"sequenceDiagram;\n Client app->>GraphQL Server: Sends SHA-256 hash of query string to execute\n Note over GraphQL Server: Fails to find persisted query string\n GraphQL Server->>Client app: Responds with error\n Client app->>GraphQL Server: Sends both query string AND hash\n Note over GraphQL Server: Persists query string and hash\n GraphQL Server->>Client app: Executes query and returns result\n Note over Client app: Time passes\n Client app->>GraphQL Server: Sends SHA-256 hash of query string to execute\n Note over GraphQL Server: Finds persisted query string\n GraphQL Server->>Client app: Executes query and returns result",mdxType:"Mermaid"}),(0,s.kt)("p",null,"Persisted queries are especially effective when clients send queries as GET requests.\nThis enables clients to take advantage of the browser cache and integrate with a CDN."),(0,s.kt)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.kt)("h2",{id:"setup"},"Setup"),(0,s.kt)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.kt)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n// You need to provide a PSR compatible cache and a TTL for queries. The best cache would be some kind\n// of in-memory cache with a limit on number of entries to make sure your cache can't be maliciously spammed with queries.\n$builder->useAutomaticPersistedQueries($cache, new DateInterval('PT1H'));\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1edb88e5.566a704c.js b/assets/js/1edb88e5.5417dcb2.js similarity index 99% rename from assets/js/1edb88e5.566a704c.js rename to assets/js/1edb88e5.5417dcb2.js index 5a084163e7..a1cb8e1cbb 100644 --- a/assets/js/1edb88e5.566a704c.js +++ b/assets/js/1edb88e5.5417dcb2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7337],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),l=n(2466),o=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),f(e)}),[s,f,i]),tabValues:i}}var y=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,l.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},l,{className:(0,i.Z)("tabs__item",b.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,y.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},3639:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>p,frontMatter:()=>i,metadata:()=>o,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},l=void 0,o={unversionedId:"extend-input-type",id:"version-6.1/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/extend-input-type.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/multiple-output-types"}},u={},s=[],c={toc:s},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7337],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),l=n(2466),o=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),f(e)}),[s,f,i]),tabValues:i}}var y=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,l.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},l,{className:(0,i.Z)("tabs__item",b.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,y.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},3639:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>p,frontMatter:()=>i,metadata:()=>o,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},l=void 0,o={unversionedId:"extend-input-type",id:"version-6.1/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/extend-input-type.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/multiple-output-types"}},u={},s=[],c={toc:s},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1f5af0f2.57438961.js b/assets/js/1f5af0f2.44486702.js similarity index 98% rename from assets/js/1f5af0f2.57438961.js rename to assets/js/1f5af0f2.44486702.js index 3ff32c9c24..3b306505ba 100644 --- a/assets/js/1f5af0f2.57438961.js +++ b/assets/js/1f5af0f2.44486702.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5813],{8421:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>y,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const s={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},o=void 0,i={unversionedId:"custom-output-types",id:"version-4.0/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.0/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/4.0/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/custom_output_types.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function y(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5813],{8421:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>y,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const s={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},o=void 0,i={unversionedId:"custom-output-types",id:"version-4.0/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.0/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/4.0/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/custom_output_types.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function y(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1f5e9707.8f8569d1.js b/assets/js/1f5e9707.5c27d17d.js similarity index 99% rename from assets/js/1f5e9707.8f8569d1.js rename to assets/js/1f5e9707.5c27d17d.js index 5e15cfa1bb..3c3c8ad4df 100644 --- a/assets/js/1f5e9707.8f8569d1.js +++ b/assets/js/1f5e9707.5c27d17d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2495],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),p=n(7392),c=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,p]=m({queryString:n,groupId:a}),[u,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),f=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),p(e),y(e)}),[p,y,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:p}=e;const c=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=p[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=y(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6725:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,p={unversionedId:"other-frameworks",id:"version-6.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-6.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/6.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/other-frameworks.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/6.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/6.0/queries"}},c={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n")),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new LazyContainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2495],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),p=n(7392),c=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,p]=m({queryString:n,groupId:a}),[u,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),f=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),p(e),y(e)}),[p,y,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:p}=e;const c=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=p[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=y(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6725:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,p={unversionedId:"other-frameworks",id:"version-6.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-6.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/6.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/other-frameworks.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/6.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/6.0/queries"}},c={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n")),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new LazyContainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2014e4e3.a034f37a.js b/assets/js/2014e4e3.fb5e0b97.js similarity index 98% rename from assets/js/2014e4e3.a034f37a.js rename to assets/js/2014e4e3.fb5e0b97.js index ba5384d276..3f3f86fe6e 100644 --- a/assets/js/2014e4e3.a034f37a.js +++ b/assets/js/2014e4e3.fb5e0b97.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2020],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>x});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function x(e){const t=(0,f.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},3768:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/docs/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/next/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/extend-input-type.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/next/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2020],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>x});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function x(e){const t=(0,f.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},3768:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/docs/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/next/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/extend-input-type.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/next/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/21637dff.8465a7b0.js b/assets/js/21637dff.c6ce2a3c.js similarity index 99% rename from assets/js/21637dff.8465a7b0.js rename to assets/js/21637dff.c6ce2a3c.js index 03e5a3e1a9..3221336738 100644 --- a/assets/js/21637dff.8465a7b0.js +++ b/assets/js/21637dff.c6ce2a3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8447],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},1110:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-4.2/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.2/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/4.2/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/authentication-authorization.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.2/docs",previous:{title:"User input validation",permalink:"/docs/4.2/validation"},next:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8447],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},1110:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-4.2/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.2/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/4.2/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/authentication-authorization.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.2/docs",previous:{title:"User input validation",permalink:"/docs/4.2/validation"},next:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/21a7a3b0.60047475.js b/assets/js/21a7a3b0.2c1a0984.js similarity index 99% rename from assets/js/21a7a3b0.60047475.js rename to assets/js/21a7a3b0.2c1a0984.js index a0c198004f..6a34d4506a 100644 --- a/assets/js/21a7a3b0.60047475.js +++ b/assets/js/21a7a3b0.2c1a0984.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2733],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},2538:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const i={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},o=void 0,l={unversionedId:"autowiring",id:"version-6.1/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-6.1/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/autowiring.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/type-mapping"},next:{title:"Extending a type",permalink:"/docs/extend-type"}},s={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2733],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},2538:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const i={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},o=void 0,l={unversionedId:"autowiring",id:"version-6.1/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-6.1/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/autowiring.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/type-mapping"},next:{title:"Extending a type",permalink:"/docs/extend-type"}},s={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/21cde469.284b5d64.js b/assets/js/21cde469.b4e8e7ed.js similarity index 99% rename from assets/js/21cde469.284b5d64.js rename to assets/js/21cde469.b4e8e7ed.js index 9a58588233..c0317422cd 100644 --- a/assets/js/21cde469.284b5d64.js +++ b/assets/js/21cde469.b4e8e7ed.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4367],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},8132:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.2/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.2/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.2/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/error-handling.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.2/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.2/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.2/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4367],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},8132:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.2/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.2/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.2/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/error-handling.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.2/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.2/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.2/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/22e1e32f.1f2952ae.js b/assets/js/22e1e32f.00eae62a.js similarity index 99% rename from assets/js/22e1e32f.1f2952ae.js rename to assets/js/22e1e32f.00eae62a.js index 9c038b04e5..9c5052322e 100644 --- a/assets/js/22e1e32f.1f2952ae.js +++ b/assets/js/22e1e32f.00eae62a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9226],{9326:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-6.0/changelog",title:"Changelog",description:"5.0.0",source:"@site/versioned_docs/version-6.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/6.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/CHANGELOG.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/6.0/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9226],{9326:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-6.0/changelog",title:"Changelog",description:"5.0.0",source:"@site/versioned_docs/version-6.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/6.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/CHANGELOG.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/6.0/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2355609d.2cd9bbbe.js b/assets/js/2355609d.46e2b30f.js similarity index 97% rename from assets/js/2355609d.2cd9bbbe.js rename to assets/js/2355609d.46e2b30f.js index fe8762405c..3d2be433e9 100644 --- a/assets/js/2355609d.2cd9bbbe.js +++ b/assets/js/2355609d.46e2b30f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1471],{3148:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-4.3/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.3/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/4.3/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/universal-service-providers.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-4.3/docs",previous:{title:"Laravel package",permalink:"/docs/4.3/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.3/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1471],{3148:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-4.3/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.3/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/4.3/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/universal-service-providers.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-4.3/docs",previous:{title:"Laravel package",permalink:"/docs/4.3/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.3/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/23794275.393c831b.js b/assets/js/23794275.d9e24816.js similarity index 99% rename from assets/js/23794275.393c831b.js rename to assets/js/23794275.d9e24816.js index e49b796a80..ccb7439ec7 100644 --- a/assets/js/23794275.393c831b.js +++ b/assets/js/23794275.d9e24816.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4076],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),s=t(6550),i=t(1980),u=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[i,u]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=t(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:n,block:t,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=u[t].value;a!==s&&(c(n),i(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",k.tabItem,r?.className,{"tabs__item--active":s===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},p.createElement(f,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},9585:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-6.0/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-6.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/6.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/type-mapping.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/6.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/6.0/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/6.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/6.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\npublic function companyOrContact(int $id): Company|Contact\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,p.kt)("p",null,(0,p.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4076],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),s=t(6550),i=t(1980),u=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[i,u]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=t(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:n,block:t,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=u[t].value;a!==s&&(c(n),i(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",k.tabItem,r?.className,{"tabs__item--active":s===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},p.createElement(f,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},9585:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-6.0/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-6.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/6.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/type-mapping.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/6.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/6.0/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/6.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/6.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\npublic function companyOrContact(int $id): Company|Contact\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,p.kt)("p",null,(0,p.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/23a8ac29.afac6f0e.js b/assets/js/23a8ac29.2756a312.js similarity index 99% rename from assets/js/23a8ac29.afac6f0e.js rename to assets/js/23a8ac29.2756a312.js index e71c553997..1b0cdc43ca 100644 --- a/assets/js/23a8ac29.afac6f0e.js +++ b/assets/js/23a8ac29.2756a312.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7110],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5449:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-5.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-5.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/5.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/validation.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-5.0/docs",previous:{title:"Error handling",permalink:"/docs/5.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/5.0/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7110],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5449:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-5.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-5.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/5.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/validation.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-5.0/docs",previous:{title:"Error handling",permalink:"/docs/5.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/5.0/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/23f642f2.8187351e.js b/assets/js/23f642f2.a399885b.js similarity index 99% rename from assets/js/23f642f2.8187351e.js rename to assets/js/23f642f2.a399885b.js index 1b361db571..bcce2daa41 100644 --- a/assets/js/23f642f2.8187351e.js +++ b/assets/js/23f642f2.a399885b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2196],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),l=n(2466),u=n(6550),i=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[l,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[i,p]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),f=(()=>{const e=i??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&u(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);u(e),p(e),y(e)}),[p,y,o]),tabValues:o}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==u&&(c(t),i(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>s.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",b.tabItem,l?.className,{"tabs__item--active":u===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function P(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},1217:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>m,frontMatter:()=>u,metadata:()=>p,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),l=n(5162);const u={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},i=void 0,p={unversionedId:"input-types",id:"version-4.1/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.1/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.1/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/input-types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-4.1/docs",previous:{title:"External type declaration",permalink:"/docs/4.1/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"}},s={},c=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,r.kt)("p",null,"Your GraphQL query might look like this:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,r.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,r.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,r.kt)("strong",{parentName:"p"},"Factory"),"."),(0,r.kt)("p",null,"A ",(0,r.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.kt)("p",null,"Here is an example of factory:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,r.kt)("p",null,"and now, you can run query like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.kt)("p",null,"A few important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,r.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,r.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,r.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,r.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,r.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,r.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.kt)("p",null,"Here is an annotated sample:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,r.kt)("p",null,"Image your ",(0,r.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2196],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),l=n(2466),u=n(6550),i=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[l,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[i,p]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),f=(()=>{const e=i??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&u(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);u(e),p(e),y(e)}),[p,y,o]),tabValues:o}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==u&&(c(t),i(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>s.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",b.tabItem,l?.className,{"tabs__item--active":u===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function P(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},1217:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>m,frontMatter:()=>u,metadata:()=>p,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),l=n(5162);const u={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},i=void 0,p={unversionedId:"input-types",id:"version-4.1/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.1/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.1/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/input-types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-4.1/docs",previous:{title:"External type declaration",permalink:"/docs/4.1/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"}},s={},c=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,r.kt)("p",null,"Your GraphQL query might look like this:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,r.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,r.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,r.kt)("strong",{parentName:"p"},"Factory"),"."),(0,r.kt)("p",null,"A ",(0,r.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.kt)("p",null,"Here is an example of factory:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,r.kt)("p",null,"and now, you can run query like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.kt)("p",null,"A few important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,r.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,r.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,r.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,r.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,r.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,r.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.kt)("p",null,"Here is an annotated sample:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,r.kt)("p",null,"Image your ",(0,r.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/242d99d9.10285b77.js b/assets/js/242d99d9.a504c308.js similarity index 95% rename from assets/js/242d99d9.10285b77.js rename to assets/js/242d99d9.a504c308.js index 64b843a829..e02c07077a 100644 --- a/assets/js/242d99d9.10285b77.js +++ b/assets/js/242d99d9.a504c308.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8773],{2108:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/troubleshooting.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-4.0/docs",previous:{title:"Internals",permalink:"/docs/4.0/internals"},next:{title:"Migrating",permalink:"/docs/4.0/migrating"}},l={},u=[],p={toc:u},d="wrapper";function c(e){let{components:t,...o}=e;return(0,r.kt)(d,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8773],{2108:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/troubleshooting.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-4.0/docs",previous:{title:"Internals",permalink:"/docs/4.0/internals"},next:{title:"Migrating",permalink:"/docs/4.0/migrating"}},l={},u=[],p={toc:u},d="wrapper";function c(e){let{components:t,...o}=e;return(0,r.kt)(d,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/24ac61c7.dda86a3c.js b/assets/js/24ac61c7.ec9e739b.js similarity index 96% rename from assets/js/24ac61c7.dda86a3c.js rename to assets/js/24ac61c7.ec9e739b.js index 101d2af266..75ab4d9be7 100644 --- a/assets/js/24ac61c7.dda86a3c.js +++ b/assets/js/24ac61c7.ec9e739b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3205],{7455:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>c});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-3.0/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-3.0/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/3.0/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},sidebar:"version-3.0/docs",previous:{title:"Input types",permalink:"/docs/3.0/input-types"},next:{title:"File uploads",permalink:"/docs/3.0/file-uploads"}},o={},c=[],p={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types would look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3205],{7455:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>c});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-3.0/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-3.0/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/3.0/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},sidebar:"version-3.0/docs",previous:{title:"Input types",permalink:"/docs/3.0/input-types"},next:{title:"File uploads",permalink:"/docs/3.0/file-uploads"}},o={},c=[],p={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types would look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/24aca886.ea81c85e.js b/assets/js/24aca886.cbe1384c.js similarity index 98% rename from assets/js/24aca886.ea81c85e.js rename to assets/js/24aca886.cbe1384c.js index 3bea4cd612..b1b3d7a988 100644 --- a/assets/js/24aca886.ea81c85e.js +++ b/assets/js/24aca886.cbe1384c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1434],{154:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},s=void 0,o={unversionedId:"internals",id:"version-4.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/internals.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},sidebar:"version-4.0/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1434],{154:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},s=void 0,o={unversionedId:"internals",id:"version-4.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/internals.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},sidebar:"version-4.0/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/263ebc7a.704a41b0.js b/assets/js/263ebc7a.ace1016a.js similarity index 99% rename from assets/js/263ebc7a.704a41b0.js rename to assets/js/263ebc7a.ace1016a.js index 4b563d1f1a..89908f1d7a 100644 --- a/assets/js/263ebc7a.704a41b0.js +++ b/assets/js/263ebc7a.ace1016a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9661],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),s=n(6550),u=n(1980),l=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,l.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=h(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,l]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!p({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);s(e),l(e),g(e)}),[l,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:s,selectValue:u,tabValues:l}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=l[n].value;a!==s&&(d(t),u(a))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},l.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":s===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},7673:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=void 0,s={unversionedId:"authentication-authorization",id:"version-6.1/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-6.1/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/authentication-authorization.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/validation"},next:{title:"Fine grained security",permalink:"/docs/fine-grained-security"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],c={toc:l},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9661],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),s=n(6550),u=n(1980),l=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,l.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=h(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,l]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!p({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);s(e),l(e),g(e)}),[l,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:s,selectValue:u,tabValues:l}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=l[n].value;a!==s&&(d(t),u(a))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},l.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":s===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},7673:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=void 0,s={unversionedId:"authentication-authorization",id:"version-6.1/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-6.1/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/authentication-authorization.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/validation"},next:{title:"Fine grained security",permalink:"/docs/fine-grained-security"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],c={toc:l},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/26662da3.7da932f7.js b/assets/js/26662da3.984614fe.js similarity index 98% rename from assets/js/26662da3.7da932f7.js rename to assets/js/26662da3.984614fe.js index a089fc0949..b14b0296d2 100644 --- a/assets/js/26662da3.7da932f7.js +++ b/assets/js/26662da3.984614fe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8757],{2275:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-3.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-3.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/3.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/internals.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/3.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8757],{2275:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-3.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-3.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/3.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/internals.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/3.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/26a27afb.853eb61b.js b/assets/js/26a27afb.24de608e.js similarity index 99% rename from assets/js/26a27afb.853eb61b.js rename to assets/js/26a27afb.24de608e.js index 7d0bd7379f..5dc8c18dec 100644 --- a/assets/js/26a27afb.853eb61b.js +++ b/assets/js/26a27afb.24de608e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1640],{4772:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-4.2/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.2/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/symfony-bundle.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-4.2/docs",previous:{title:"Getting Started",permalink:"/docs/4.2/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.2/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-4.2/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.2/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/symfony-bundle.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-4.2/docs",previous:{title:"Getting Started",permalink:"/docs/4.2/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.2/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),u=a(1980),s=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[u,s]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=u??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),h(e)}),[s,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(c(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8031:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/docs/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/next/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/custom-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/next/pagination"},next:{title:"Custom annotations",permalink:"/docs/next/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper(\n // Let's register a type that maps by default to the \"MyClass\" PHP class\n types: [\n MyClass::class => new MyCustomOutputType()\n ],\n\n // If you don't want your output type to map to any PHP class by default, use:\n notMappedTypes: [\n new MyCustomOutputType()\n ],\n);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2583],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),u=a(1980),s=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[u,s]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=u??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),h(e)}),[s,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(c(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8031:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/docs/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/next/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/custom-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/next/pagination"},next:{title:"Custom annotations",permalink:"/docs/next/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper(\n // Let's register a type that maps by default to the \"MyClass\" PHP class\n types: [\n MyClass::class => new MyCustomOutputType()\n ],\n\n // If you don't want your output type to map to any PHP class by default, use:\n notMappedTypes: [\n new MyCustomOutputType()\n ],\n);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/28c12eaf.c4469c40.js b/assets/js/28c12eaf.144e51a7.js similarity index 99% rename from assets/js/28c12eaf.c4469c40.js rename to assets/js/28c12eaf.144e51a7.js index c22b117305..200112a592 100644 --- a/assets/js/28c12eaf.c4469c40.js +++ b/assets/js/28c12eaf.144e51a7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1977],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function x(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(y,(0,r.Z)({},e,n)),a.createElement(x,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},6451:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var r=t(7462),a=(t(7294),t(3905));t(1839),t(4866),t(5162);const o={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,l={unversionedId:"error-handling",id:"version-6.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.1/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/error-handling.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/validation"}},s={},u=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],c={toc:u},p="wrapper";function h(e){let{components:n,...t}=e;return(0,a.kt)(p,(0,r.Z)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1977],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function x(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(y,(0,r.Z)({},e,n)),a.createElement(x,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},6451:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var r=t(7462),a=(t(7294),t(3905));t(1839),t(4866),t(5162);const o={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,l={unversionedId:"error-handling",id:"version-6.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.1/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/error-handling.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/validation"}},s={},u=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],c={toc:u},p="wrapper";function h(e){let{components:n,...t}=e;return(0,a.kt)(p,(0,r.Z)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/29a6c1ba.5d0cc3a8.js b/assets/js/29a6c1ba.b1fa9f48.js similarity index 99% rename from assets/js/29a6c1ba.5d0cc3a8.js rename to assets/js/29a6c1ba.b1fa9f48.js index d992e87106..0491b90965 100644 --- a/assets/js/29a6c1ba.5d0cc3a8.js +++ b/assets/js/29a6c1ba.b1fa9f48.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4211],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},9448:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.2/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.2/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/multiple-output-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.2/docs",previous:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4211],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},9448:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.2/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.2/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/multiple-output-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.2/docs",previous:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/29cf2ad6.e212db87.js b/assets/js/29cf2ad6.57b90fab.js similarity index 99% rename from assets/js/29cf2ad6.e212db87.js rename to assets/js/29cf2ad6.57b90fab.js index 8eae64b470..be36338e59 100644 --- a/assets/js/29cf2ad6.e212db87.js +++ b/assets/js/29cf2ad6.57b90fab.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8348],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},1946:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/docs/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/next/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/symfony-bundle-advanced.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/next/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/next/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8348],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},1946:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/docs/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/next/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/symfony-bundle-advanced.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/next/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/next/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2b26025e.a6ff5151.js b/assets/js/2b26025e.22ae6ab5.js similarity index 97% rename from assets/js/2b26025e.a6ff5151.js rename to assets/js/2b26025e.22ae6ab5.js index af5de7fb6a..d93a05d60a 100644 --- a/assets/js/2b26025e.a6ff5151.js +++ b/assets/js/2b26025e.22ae6ab5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7046],{7250:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={unversionedId:"index",id:"version-6.1/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-6.1/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/README.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/getting-started"}},s={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7046],{7250:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={unversionedId:"index",id:"version-6.1/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-6.1/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/README.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/getting-started"}},s={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2bbfc5d5.428785b5.js b/assets/js/2bbfc5d5.891ea6bc.js similarity index 99% rename from assets/js/2bbfc5d5.428785b5.js rename to assets/js/2bbfc5d5.891ea6bc.js index 9a902cb7ce..1ebcbbbb7b 100644 --- a/assets/js/2bbfc5d5.428785b5.js +++ b/assets/js/2bbfc5d5.891ea6bc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2978],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),o=a(6550),i=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[i,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=i??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==o&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},8419:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const o={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},i=void 0,p={unversionedId:"multiple_output_types",id:"version-3.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/3.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/multiple_output_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/3.0/external_type_declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2978],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),o=a(6550),i=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[i,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=i??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==o&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},8419:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const o={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},i=void 0,p={unversionedId:"multiple_output_types",id:"version-3.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/3.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/multiple_output_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/3.0/external_type_declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2d02c83c.16fd8047.js b/assets/js/2d02c83c.941e9cc8.js similarity index 98% rename from assets/js/2d02c83c.16fd8047.js rename to assets/js/2d02c83c.941e9cc8.js index 8c9ab2d66a..011edf93f1 100644 --- a/assets/js/2d02c83c.16fd8047.js +++ b/assets/js/2d02c83c.941e9cc8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9580],{7636:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-6.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/6.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/field-middlewares.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/6.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/6.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9580],{7636:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-6.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/6.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/field-middlewares.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/6.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/6.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/2d4548df.052db814.js b/assets/js/2d4548df.2d139f18.js similarity index 99% rename from assets/js/2d4548df.052db814.js rename to assets/js/2d4548df.2d139f18.js index c6b0d3733b..20881c7ca0 100644 --- a/assets/js/2d4548df.052db814.js +++ b/assets/js/2d4548df.2d139f18.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7022],{9617:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/docs/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/next/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/field-middlewares.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/next/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function withName(string $name): self { /* ... */ }\n public function getType() { /* ... */ }\n public function withType($type): self { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function withParameters(array $parameters): self { /* ... */ }\n public function withCallable(callable $callable): self { /* ... */ }\n public function withTargetMethodOnSource(?string $targetMethodOnSource): self { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function withInjectSource(bool $injectSource): self { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function withComment(?string $comment): self { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function withMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): self { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function withResolver(callable $resolver): self { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),", although this should be used with caution:\nfield middlewares only get called once per Schema instance. If you use a long-running server (like Laravel Octane, Swoole, RoadRunner etc)\nand share the same Schema instance across requests, you will not be able to hide fields based on request data."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7022],{9617:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/docs/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/next/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/field-middlewares.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/next/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function withName(string $name): self { /* ... */ }\n public function getType() { /* ... */ }\n public function withType($type): self { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function withParameters(array $parameters): self { /* ... */ }\n public function withCallable(callable $callable): self { /* ... */ }\n public function withTargetMethodOnSource(?string $targetMethodOnSource): self { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function withInjectSource(bool $injectSource): self { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function withComment(?string $comment): self { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function withMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): self { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function withResolver(callable $resolver): self { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),", although this should be used with caution:\nfield middlewares only get called once per Schema instance. If you use a long-running server (like Laravel Octane, Swoole, RoadRunner etc)\nand share the same Schema instance across requests, you will not be able to hide fields based on request data."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/2e25c87f.4b68e812.js b/assets/js/2e25c87f.616c2a7f.js similarity index 99% rename from assets/js/2e25c87f.4b68e812.js rename to assets/js/2e25c87f.616c2a7f.js index 60548406d9..213bbe6a67 100644 --- a/assets/js/2e25c87f.4b68e812.js +++ b/assets/js/2e25c87f.616c2a7f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5515],{5566:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var a=n(7462),l=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},i=void 0,o={unversionedId:"symfony-bundle",id:"symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/docs/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/next/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/symfony-bundle.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/next/getting-started"},next:{title:"Laravel package",permalink:"/docs/next/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:s},d="wrapper";function u(e){let{components:t,...n}=e;return(0,l.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,l.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,l.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,l.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,l.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.kt)("p",null,"Now, go to the ",(0,l.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,l.kt)("p",null,"More advanced parameters are detailed in the ",(0,l.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,l.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,l.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,l.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var a=n(7462),l=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},i=void 0,o={unversionedId:"symfony-bundle",id:"symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/docs/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/next/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/symfony-bundle.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/next/getting-started"},next:{title:"Laravel package",permalink:"/docs/next/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:s},d="wrapper";function u(e){let{components:t,...n}=e;return(0,l.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,l.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,l.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,l.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,l.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.kt)("p",null,"Now, go to the ",(0,l.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,l.kt)("p",null,"More advanced parameters are detailed in the ",(0,l.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,l.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,l.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,l.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-4.3/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.3/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/4.3/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/annotations-reference.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-4.3/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.3/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.3/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5231],{4892:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-4.3/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.3/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/4.3/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/annotations-reference.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-4.3/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.3/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.3/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.3/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2ef99682.0371e183.js b/assets/js/2ef99682.67e711bf.js similarity index 99% rename from assets/js/2ef99682.0371e183.js rename to assets/js/2ef99682.67e711bf.js index f1e9aa7d40..937a8f4989 100644 --- a/assets/js/2ef99682.0371e183.js +++ b/assets/js/2ef99682.67e711bf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4374],{8502:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const o={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},s=void 0,i={unversionedId:"custom-output-types",id:"version-3.0/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-3.0/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/3.0/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/custom_output_types.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},sidebar:"version-3.0/docs",previous:{title:"Pagination",permalink:"/docs/3.0/pagination"},next:{title:"Troubleshooting",permalink:"/docs/3.0/troubleshooting"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function c(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4374],{8502:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const o={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},s=void 0,i={unversionedId:"custom-output-types",id:"version-3.0/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-3.0/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/3.0/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/custom_output_types.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},sidebar:"version-3.0/docs",previous:{title:"Pagination",permalink:"/docs/3.0/pagination"},next:{title:"Troubleshooting",permalink:"/docs/3.0/troubleshooting"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function c(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2f36012a.46661587.js b/assets/js/2f36012a.b37caaa7.js similarity index 98% rename from assets/js/2f36012a.46661587.js rename to assets/js/2f36012a.b37caaa7.js index 3987c0d4d9..3481370859 100644 --- a/assets/js/2f36012a.46661587.js +++ b/assets/js/2f36012a.b37caaa7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8197],{9461:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-5.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-5.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/5.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/implementing-security.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-5.0/docs",previous:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/5.0/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8197],{9461:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-5.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-5.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/5.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/implementing-security.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-5.0/docs",previous:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/5.0/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/30940d42.134f49ec.js b/assets/js/30940d42.47c1861a.js similarity index 99% rename from assets/js/30940d42.134f49ec.js rename to assets/js/30940d42.47c1861a.js index 8b8cb36f6b..c31553e71a 100644 --- a/assets/js/30940d42.134f49ec.js +++ b/assets/js/30940d42.47c1861a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6786],{1144:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-5.0/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/5.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/symfony-bundle.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-5.0/docs",previous:{title:"Getting Started",permalink:"/docs/5.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/5.0/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-5.0/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/5.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/symfony-bundle.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-5.0/docs",previous:{title:"Getting Started",permalink:"/docs/5.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/5.0/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/getting-started.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-4.0/docs",previous:{title:"GraphQLite",permalink:"/docs/4.0/"},next:{title:"Symfony bundle",permalink:"/docs/4.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3236],{9400:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/getting-started.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-4.0/docs",previous:{title:"GraphQLite",permalink:"/docs/4.0/"},next:{title:"Symfony bundle",permalink:"/docs/4.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/346bcb92.39f9f3c7.js b/assets/js/346bcb92.95778f9b.js similarity index 98% rename from assets/js/346bcb92.39f9f3c7.js rename to assets/js/346bcb92.95778f9b.js index 72c9175d93..8bb0ed2e61 100644 --- a/assets/js/346bcb92.39f9f3c7.js +++ b/assets/js/346bcb92.95778f9b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[222],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},1292:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-5.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-5.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/5.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/pagination.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-5.0/docs",previous:{title:"File uploads",permalink:"/docs/5.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/5.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[222],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},1292:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-5.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-5.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/5.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/pagination.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-5.0/docs",previous:{title:"File uploads",permalink:"/docs/5.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/5.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/354a9b78.d904d69b.js b/assets/js/354a9b78.4a28b27c.js similarity index 97% rename from assets/js/354a9b78.d904d69b.js rename to assets/js/354a9b78.4a28b27c.js index 1e64909a87..0fa92917be 100644 --- a/assets/js/354a9b78.d904d69b.js +++ b/assets/js/354a9b78.4a28b27c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9752],{8288:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},r=void 0,l={unversionedId:"extend_input_type",id:"version-4.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/4.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/extend_input_type.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},sidebar:"version-4.0/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.0/multiple_output_types"}},p={},d=[],s={toc:d},u="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(u,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.kt)("code",null,"@Factory")," tag, ",(0,i.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.kt)("p",null,"Just like with output type (that can be ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/extend_type"},"extended using the ",(0,i.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,i.kt)("div",{class:"alert alert--info"},"The ",(0,i.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,i.kt)("code",null,"@Factory")," method. This can happen if the ",(0,i.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,i.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")),(0,i.kt)("p",null,"Assuming you ",(0,i.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")),(0,i.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.kt)("p",null,"A few things to notice:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,i.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9752],{8288:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},r=void 0,l={unversionedId:"extend_input_type",id:"version-4.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/4.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/extend_input_type.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},sidebar:"version-4.0/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.0/multiple_output_types"}},p={},d=[],s={toc:d},u="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(u,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.kt)("code",null,"@Factory")," tag, ",(0,i.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.kt)("p",null,"Just like with output type (that can be ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/extend_type"},"extended using the ",(0,i.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,i.kt)("div",{class:"alert alert--info"},"The ",(0,i.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,i.kt)("code",null,"@Factory")," method. This can happen if the ",(0,i.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,i.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")),(0,i.kt)("p",null,"Assuming you ",(0,i.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")),(0,i.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.kt)("p",null,"A few things to notice:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,i.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/366cfce3.266ad45e.js b/assets/js/366cfce3.185a20a6.js similarity index 99% rename from assets/js/366cfce3.266ad45e.js rename to assets/js/366cfce3.185a20a6.js index 6d8cca174a..fc0a0254d7 100644 --- a/assets/js/366cfce3.266ad45e.js +++ b/assets/js/366cfce3.185a20a6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3021],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},4393:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-4.2/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.2/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.2/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/queries.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-4.2/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.2/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.2/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3021],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},4393:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-4.2/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.2/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.2/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/queries.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-4.2/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.2/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.2/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/36ddade1.0575f8ab.js b/assets/js/36ddade1.dec2ebb3.js similarity index 94% rename from assets/js/36ddade1.0575f8ab.js rename to assets/js/36ddade1.dec2ebb3.js index 4f16b1388e..fe4f9443a1 100644 --- a/assets/js/36ddade1.0575f8ab.js +++ b/assets/js/36ddade1.dec2ebb3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7456],{9058:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-6.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-6.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/6.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/getting-started.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.0/"},next:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7456],{9058:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-6.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-6.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/6.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/getting-started.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.0/"},next:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/379bfe51.3040a372.js b/assets/js/379bfe51.699532e6.js similarity index 99% rename from assets/js/379bfe51.3040a372.js rename to assets/js/379bfe51.699532e6.js index 96edbd795f..e344e1ba88 100644 --- a/assets/js/379bfe51.3040a372.js +++ b/assets/js/379bfe51.699532e6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6107],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},7633:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>i,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},s=void 0,u={unversionedId:"pagination",id:"version-4.1/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.1/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.1/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/pagination.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-4.1/docs",previous:{title:"File uploads",permalink:"/docs/4.1/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.1/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6107],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},7633:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>i,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},s=void 0,u={unversionedId:"pagination",id:"version-4.1/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.1/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.1/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/pagination.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-4.1/docs",previous:{title:"File uploads",permalink:"/docs/4.1/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.1/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/38317547.969710aa.js b/assets/js/38317547.062642d0.js similarity index 96% rename from assets/js/38317547.969710aa.js rename to assets/js/38317547.062642d0.js index 06ee12da51..df96e7ac7e 100644 --- a/assets/js/38317547.969710aa.js +++ b/assets/js/38317547.062642d0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4773],{6739:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-4.1/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-4.1/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/4.1/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/inheritance.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"}},c={},o=[],p={toc:o},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4773],{6739:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-4.1/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-4.1/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/4.1/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/inheritance.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"}},c={},o=[],p={toc:o},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/38cf1c7a.facab26b.js b/assets/js/38cf1c7a.e3aa5eda.js similarity index 99% rename from assets/js/38cf1c7a.facab26b.js rename to assets/js/38cf1c7a.e3aa5eda.js index 38bc45c75e..1364bae2d5 100644 --- a/assets/js/38cf1c7a.facab26b.js +++ b/assets/js/38cf1c7a.e3aa5eda.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8368],{3581:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/field_middlewares.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},sidebar:"version-4.0/docs",previous:{title:"Custom types",permalink:"/docs/4.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8368],{3581:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/field_middlewares.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations",original_id:"field-middlewares"},sidebar:"version-4.0/docs",previous:{title:"Custom types",permalink:"/docs/4.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/394f3211.3e6aed2c.js b/assets/js/394f3211.9412d7df.js similarity index 99% rename from assets/js/394f3211.3e6aed2c.js rename to assets/js/394f3211.9412d7df.js index dc4f5fb7f4..5c63f06cd0 100644 --- a/assets/js/394f3211.3e6aed2c.js +++ b/assets/js/394f3211.9412d7df.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3096],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),f(e)}),[u,f,l]),tabValues:l}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},8677:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const l={id:"queries",title:"Queries",sidebar_label:"Queries"},o=void 0,i={unversionedId:"queries",id:"version-6.1/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-6.1/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/queries.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/other-frameworks"},next:{title:"Mutations",permalink:"/docs/mutations"}},s={},u=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],p={toc:u},c="wrapper";function d(e){let{components:t,...l}=e;return(0,r.kt)(c,(0,n.Z)({},p,l,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:a(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,a)=>{a.d(t,{Z:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3096],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),f(e)}),[u,f,l]),tabValues:l}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},8677:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const l={id:"queries",title:"Queries",sidebar_label:"Queries"},o=void 0,i={unversionedId:"queries",id:"version-6.1/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-6.1/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/queries.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/other-frameworks"},next:{title:"Mutations",permalink:"/docs/mutations"}},s={},u=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],p={toc:u},c="wrapper";function d(e){let{components:t,...l}=e;return(0,r.kt)(c,(0,n.Z)({},p,l,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:a(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,a)=>{a.d(t,{Z:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/3b486936.d0e8621f.js b/assets/js/3b486936.8dc0317b.js similarity index 97% rename from assets/js/3b486936.d0e8621f.js rename to assets/js/3b486936.8dc0317b.js index 9692cb1d30..59efca27e6 100644 --- a/assets/js/3b486936.d0e8621f.js +++ b/assets/js/3b486936.8dc0317b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8334],{1863:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-5.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-5.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/5.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/troubleshooting.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-5.0/docs",previous:{title:"Internals",permalink:"/docs/5.0/internals"},next:{title:"Migrating",permalink:"/docs/5.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8334],{1863:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-5.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-5.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/5.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/troubleshooting.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-5.0/docs",previous:{title:"Internals",permalink:"/docs/5.0/internals"},next:{title:"Migrating",permalink:"/docs/5.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/3d0eb74d.262e46a4.js b/assets/js/3d0eb74d.72c38bde.js similarity index 99% rename from assets/js/3d0eb74d.262e46a4.js rename to assets/js/3d0eb74d.72c38bde.js index ebfb2ed500..10fd65e04f 100644 --- a/assets/js/3d0eb74d.262e46a4.js +++ b/assets/js/3d0eb74d.72c38bde.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3100],{8634:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-4.3/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.3/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/symfony-bundle.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-4.3/docs",previous:{title:"Getting Started",permalink:"/docs/4.3/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.3/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-4.3/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.3/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/symfony-bundle.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"version-4.3/docs",previous:{title:"Getting Started",permalink:"/docs/4.3/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.3/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=h({queryString:n,groupId:a}),[c,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),f(e)}),[s,f,i]),tabValues:i}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=s[n].value;a!==l&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},o,{className:(0,i.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(b,(0,a.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},2725:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={unversionedId:"input-types",id:"version-6.1/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-6.1/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/input-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/inheritance-interfaces"}},u={},s=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],p={toc:s},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,r.kt)("p",null,"Your GraphQL query might look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,r.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,r.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,r.kt)("a",{parentName:"p",href:"input-attribute"},(0,r.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,r.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,r.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,r.kt)("p",null,"Now if you call the ",(0,r.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,r.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,r.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,r.kt)("p",null,"There are some important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,r.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,r.kt)("ul",{parentName:"li"},(0,r.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,r.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,r.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,r.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,r.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,r.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,r.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,r.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,r.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,r.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,r.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,r.kt)("p",null,"Simple usage of the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,r.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,r.kt)("p",null,"You can add multiple ",(0,r.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n")),(0,r.kt)("p",null,"There are 2 input types added to the ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,r.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,r.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,r.kt)("p",null,"Note that ",(0,r.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,r.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,r.kt)("h2",{id:"factory"},"Factory"),(0,r.kt)("p",null,"A ",(0,r.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.kt)("p",null,"Here is an example of factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,r.kt)("p",null,"and now, you can run query like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.kt)("p",null,"A few important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,r.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,r.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,r.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,r.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,r.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\npublic function getProductById(#[UseInputType(inputType:"ID!")] string $id): Product {\n return $this->productRepository->findById($id);\n}\n')),(0,r.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.kt)("p",null,"Here is an annotated sample:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')),(0,r.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,r.kt)("p",null,"Image your ",(0,r.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n")),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[439],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=h({queryString:n,groupId:a}),[c,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),f(e)}),[s,f,i]),tabValues:i}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=s[n].value;a!==l&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},o,{className:(0,i.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(b,(0,a.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},2725:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={unversionedId:"input-types",id:"version-6.1/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-6.1/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/input-types.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/inheritance-interfaces"}},u={},s=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],p={toc:s},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,r.kt)("p",null,"Your GraphQL query might look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,r.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,r.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,r.kt)("a",{parentName:"p",href:"input-attribute"},(0,r.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,r.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,r.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,r.kt)("p",null,"Now if you call the ",(0,r.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,r.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,r.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,r.kt)("p",null,"There are some important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,r.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,r.kt)("ul",{parentName:"li"},(0,r.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,r.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,r.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,r.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,r.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,r.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,r.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,r.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,r.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,r.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,r.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,r.kt)("p",null,"Simple usage of the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,r.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,r.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,r.kt)("p",null,"You can add multiple ",(0,r.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n")),(0,r.kt)("p",null,"There are 2 input types added to the ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,r.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,r.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,r.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,r.kt)("li",{parentName:"ul"},"Field ",(0,r.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,r.kt)("p",null,"Note that ",(0,r.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,r.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,r.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,r.kt)("h2",{id:"factory"},"Factory"),(0,r.kt)("p",null,"A ",(0,r.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.kt)("p",null,"Here is an example of factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,r.kt)("p",null,"and now, you can run query like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.kt)("p",null,"A few important things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,r.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,r.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,r.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,r.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,r.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\npublic function getProductById(#[UseInputType(inputType:"ID!")] string $id): Product {\n return $this->productRepository->findById($id);\n}\n')),(0,r.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,r.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.kt)("p",null,"Here is an annotated sample:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')),(0,r.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,r.kt)("p",null,"Image your ",(0,r.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n")),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/3f944aba.9bb9b1a0.js b/assets/js/3f944aba.796d879a.js similarity index 97% rename from assets/js/3f944aba.9bb9b1a0.js rename to assets/js/3f944aba.796d879a.js index efcbf8a53c..031a5c2257 100644 --- a/assets/js/3f944aba.9bb9b1a0.js +++ b/assets/js/3f944aba.796d879a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7500],{3958:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-4.2/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.2/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/4.2/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/universal-service-providers.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-4.2/docs",previous:{title:"Laravel package",permalink:"/docs/4.2/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.2/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7500],{3958:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-4.2/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.2/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/4.2/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/universal-service-providers.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-4.2/docs",previous:{title:"Laravel package",permalink:"/docs/4.2/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.2/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/400ddbbb.72daa855.js b/assets/js/400ddbbb.6dc8b14d.js similarity index 99% rename from assets/js/400ddbbb.72daa855.js rename to assets/js/400ddbbb.6dc8b14d.js index 499386e4ca..86cf8b159b 100644 --- a/assets/js/400ddbbb.72daa855.js +++ b/assets/js/400ddbbb.6dc8b14d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6904],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6777:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-6.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-6.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/6.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/mutations.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/6.0/queries"},next:{title:"Type mapping",permalink:"/docs/6.0/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6904],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6777:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-6.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-6.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/6.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/mutations.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/6.0/queries"},next:{title:"Type mapping",permalink:"/docs/6.0/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/471c3e37.0598913d.js b/assets/js/471c3e37.27163584.js similarity index 98% rename from assets/js/471c3e37.0598913d.js rename to assets/js/471c3e37.27163584.js index c372a6d456..922440c083 100644 --- a/assets/js/471c3e37.0598913d.js +++ b/assets/js/471c3e37.27163584.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3771],{5272:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/docs/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/next/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/argument-resolving.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/next/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3771],{5272:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/docs/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/next/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/argument-resolving.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/next/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/48fde361.a1aa5712.js b/assets/js/48fde361.ffab8f86.js similarity index 99% rename from assets/js/48fde361.a1aa5712.js rename to assets/js/48fde361.ffab8f86.js index 6967cb95eb..9990dc7058 100644 --- a/assets/js/48fde361.a1aa5712.js +++ b/assets/js/48fde361.ffab8f86.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3059],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},5335:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.3/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.3/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.3/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/inheritance-interfaces.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-4.3/docs",previous:{title:"Input types",permalink:"/docs/4.3/input-types"},next:{title:"Error handling",permalink:"/docs/4.3/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3059],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},5335:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.3/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.3/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.3/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/inheritance-interfaces.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-4.3/docs",previous:{title:"Input types",permalink:"/docs/4.3/input-types"},next:{title:"Error handling",permalink:"/docs/4.3/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4a060504.298cb183.js b/assets/js/4a060504.87c44a25.js similarity index 98% rename from assets/js/4a060504.298cb183.js rename to assets/js/4a060504.87c44a25.js index 51ff4d5b94..c1ee3cb2b7 100644 --- a/assets/js/4a060504.298cb183.js +++ b/assets/js/4a060504.87c44a25.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6724],{172:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.3/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.3/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.3/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/migrating.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-4.3/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.3/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.3/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.3/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6724],{172:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.3/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.3/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.3/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/migrating.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-4.3/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.3/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.3/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.3/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4a07aaf0.f104366d.js b/assets/js/4a07aaf0.c8c241c7.js similarity index 98% rename from assets/js/4a07aaf0.f104366d.js rename to assets/js/4a07aaf0.c8c241c7.js index c6bcafbcc1..3a43546b04 100644 --- a/assets/js/4a07aaf0.f104366d.js +++ b/assets/js/4a07aaf0.c8c241c7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6596],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),u=n(2466),o=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==o&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:u}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},u,{className:(0,l.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},4750:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),u=n(5162);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-3.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-3.0/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/3.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/query_plan.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6596],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),u=n(2466),o=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==o&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:u}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},u,{className:(0,l.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},4750:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),u=n(5162);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-3.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-3.0/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/3.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/query_plan.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4a2da18c.112fae41.js b/assets/js/4a2da18c.8c8cf89a.js similarity index 98% rename from assets/js/4a2da18c.112fae41.js rename to assets/js/4a2da18c.8c8cf89a.js index e49028387b..943c8dda4e 100644 --- a/assets/js/4a2da18c.112fae41.js +++ b/assets/js/4a2da18c.8c8cf89a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6259],{6667:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-5.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/5.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/field-middlewares.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-5.0/docs",previous:{title:"Custom types",permalink:"/docs/5.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/5.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6259],{6667:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-5.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/5.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/field-middlewares.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-5.0/docs",previous:{title:"Custom types",permalink:"/docs/5.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/5.0/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/4aab8b8c.65c7aad0.js b/assets/js/4aab8b8c.4ce6ea9e.js similarity index 99% rename from assets/js/4aab8b8c.65c7aad0.js rename to assets/js/4aab8b8c.4ce6ea9e.js index 84e593a0e0..3468c921a8 100644 --- a/assets/js/4aab8b8c.65c7aad0.js +++ b/assets/js/4aab8b8c.4ce6ea9e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5544],{4655:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/argument_resolving.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},sidebar:"version-4.0/docs",previous:{title:"Custom annotations",permalink:"/docs/4.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.0/extend_input_type"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},d="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5544],{4655:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/argument_resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/argument_resolving.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving",original_id:"argument-resolving"},sidebar:"version-4.0/docs",previous:{title:"Custom annotations",permalink:"/docs/4.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.0/extend_input_type"}},s={},m=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],p={toc:m},d="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.kt)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.kt)("li",{parentName:"ul"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4bdafdff.fe870ace.js b/assets/js/4bdafdff.97cc0e41.js similarity index 99% rename from assets/js/4bdafdff.fe870ace.js rename to assets/js/4bdafdff.97cc0e41.js index 31ef6786ae..bbf219efc1 100644 --- a/assets/js/4bdafdff.fe870ace.js +++ b/assets/js/4bdafdff.97cc0e41.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8198],{2254:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-6.0/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-6.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/6.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/annotations-reference.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/6.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/6.0/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8198],{2254:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-6.0/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-6.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/6.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/annotations-reference.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/6.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/6.0/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/6.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4c7f7507.b955a503.js b/assets/js/4c7f7507.492c852a.js similarity index 99% rename from assets/js/4c7f7507.b955a503.js rename to assets/js/4c7f7507.492c852a.js index afbba21fd8..76b8da3765 100644 --- a/assets/js/4c7f7507.b955a503.js +++ b/assets/js/4c7f7507.492c852a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8100],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7901:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.1/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.1/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.1/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/inheritance-interfaces.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},sidebar:"version-4.1/docs",previous:{title:"Input types",permalink:"/docs/4.1/input-types"},next:{title:"Error handling",permalink:"/docs/4.1/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8100],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7901:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.1/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.1/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.1/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/inheritance-interfaces.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},sidebar:"version-4.1/docs",previous:{title:"Input types",permalink:"/docs/4.1/input-types"},next:{title:"Error handling",permalink:"/docs/4.1/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d00e03a.d6388d9e.js b/assets/js/4d00e03a.437691d8.js similarity index 99% rename from assets/js/4d00e03a.d6388d9e.js rename to assets/js/4d00e03a.437691d8.js index ccabb09fb6..7c2bab9350 100644 --- a/assets/js/4d00e03a.d6388d9e.js +++ b/assets/js/4d00e03a.437691d8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5091],{3116:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-4.2/changelog",title:"Changelog",description:"4.2.0",source:"@site/versioned_docs/version-4.2/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.2/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/CHANGELOG.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-4.2/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.2/semver"}},p={},d=[{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5091],{3116:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-4.2/changelog",title:"Changelog",description:"4.2.0",source:"@site/versioned_docs/version-4.2/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.2/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/CHANGELOG.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-4.2/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.2/semver"}},p={},d=[{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d049718.71949449.js b/assets/js/4d049718.4f1b4174.js similarity index 99% rename from assets/js/4d049718.71949449.js rename to assets/js/4d049718.4f1b4174.js index ff9c4c2f10..98e315ad79 100644 --- a/assets/js/4d049718.71949449.js +++ b/assets/js/4d049718.4f1b4174.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8037],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},3235:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-5.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-5.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/5.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/external-type-declaration.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-5.0/docs",previous:{title:"Extending a type",permalink:"/docs/5.0/extend-type"},next:{title:"Input types",permalink:"/docs/5.0/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("p",null,"You can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"You can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/5.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8037],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},3235:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-5.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-5.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/5.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/external-type-declaration.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-5.0/docs",previous:{title:"Extending a type",permalink:"/docs/5.0/extend-type"},next:{title:"Input types",permalink:"/docs/5.0/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("p",null,"You can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"You can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/5.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d68b066.6a49e0b5.js b/assets/js/4d68b066.5650e6de.js similarity index 97% rename from assets/js/4d68b066.6a49e0b5.js rename to assets/js/4d68b066.5650e6de.js index 0cd9133918..216e0a9e00 100644 --- a/assets/js/4d68b066.6a49e0b5.js +++ b/assets/js/4d68b066.5650e6de.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2612],{9978:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},o=void 0,s={unversionedId:"semver",id:"version-4.1/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-4.1/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.1/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/semver.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.1/docs",previous:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.1/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,n.kt)(d,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2612],{9978:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},o=void 0,s={unversionedId:"semver",id:"version-4.1/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-4.1/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.1/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/semver.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.1/docs",previous:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.1/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,n.kt)(d,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4dd5816e.e078b8af.js b/assets/js/4dd5816e.0df8298c.js similarity index 99% rename from assets/js/4dd5816e.e078b8af.js rename to assets/js/4dd5816e.0df8298c.js index b0b91eaa8e..15b1e541a7 100644 --- a/assets/js/4dd5816e.e078b8af.js +++ b/assets/js/4dd5816e.0df8298c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4762],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},2391:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-6.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-6.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/6.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/fine-grained-security.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/6.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/6.0/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4762],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},2391:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-6.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-6.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/6.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/fine-grained-security.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/6.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/6.0/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4dfeb783.22a2b26a.js b/assets/js/4dfeb783.a32bd5fa.js similarity index 99% rename from assets/js/4dfeb783.22a2b26a.js rename to assets/js/4dfeb783.a32bd5fa.js index 7e743cdc9c..60d7c3860b 100644 --- a/assets/js/4dfeb783.22a2b26a.js +++ b/assets/js/4dfeb783.a32bd5fa.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8299],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},7159:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.3/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.3/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/multiple-output-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.3/docs",previous:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8299],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},7159:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.3/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.3/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/multiple-output-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.3/docs",previous:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.3/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4e1a0951.93fffe13.js b/assets/js/4e1a0951.1f1b32c1.js similarity index 99% rename from assets/js/4e1a0951.93fffe13.js rename to assets/js/4e1a0951.1f1b32c1.js index 4ee0c028c3..d8d5dee0ac 100644 --- a/assets/js/4e1a0951.93fffe13.js +++ b/assets/js/4e1a0951.1f1b32c1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[251],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3132:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-3.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-3.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/3.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/laravel-package-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"}},p={},c=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'```php\n/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[251],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3132:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-3.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-3.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/3.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/laravel-package-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"}},p={},c=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'```php\n/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4e73bd72.2972a3d8.js b/assets/js/4e73bd72.f90df4ab.js similarity index 96% rename from assets/js/4e73bd72.2972a3d8.js rename to assets/js/4e73bd72.f90df4ab.js index 964f572a69..b79b77d428 100644 --- a/assets/js/4e73bd72.2972a3d8.js +++ b/assets/js/4e73bd72.f90df4ab.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4280],{4689:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,r={unversionedId:"mutations",id:"version-3.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-3.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/3.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/mutations.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-3.0/docs",previous:{title:"Queries",permalink:"/docs/3.0/queries"},next:{title:"Type mapping",permalink:"/docs/3.0/type_mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(p,(0,a.Z)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/3.0/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4280],{4689:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,r={unversionedId:"mutations",id:"version-3.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-3.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/3.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/mutations.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-3.0/docs",previous:{title:"Queries",permalink:"/docs/3.0/queries"},next:{title:"Type mapping",permalink:"/docs/3.0/type_mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(p,(0,a.Z)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In GraphQLite, mutations are created ",(0,i.kt)("a",{parentName:"p",href:"/docs/3.0/queries"},"like queries"),"."),(0,i.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f30448a.ff7b6a26.js b/assets/js/4f30448a.031bc330.js similarity index 99% rename from assets/js/4f30448a.ff7b6a26.js rename to assets/js/4f30448a.031bc330.js index 3e88c286ec..ac4c707f3d 100644 --- a/assets/js/4f30448a.ff7b6a26.js +++ b/assets/js/4f30448a.031bc330.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8475],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},7011:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-3.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-3.0/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/3.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/error_handling.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/3.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8475],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},7011:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-3.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-3.0/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/3.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/error_handling.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/3.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f4b6633.4ded7e42.js b/assets/js/4f4b6633.361110e8.js similarity index 99% rename from assets/js/4f4b6633.4ded7e42.js rename to assets/js/4f4b6633.361110e8.js index fbc01c61f4..6bc7f7a9cc 100644 --- a/assets/js/4f4b6633.4ded7e42.js +++ b/assets/js/4f4b6633.361110e8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9293],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},6218:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-5.0/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-5.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/5.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/type-mapping.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-5.0/docs",previous:{title:"Mutations",permalink:"/docs/5.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/5.0/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/5.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/5.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9293],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},6218:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-5.0/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-5.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/5.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/type-mapping.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-5.0/docs",previous:{title:"Mutations",permalink:"/docs/5.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/5.0/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/5.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/5.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f59166d.ca2e7dd1.js b/assets/js/4f59166d.90f1a358.js similarity index 99% rename from assets/js/4f59166d.ca2e7dd1.js rename to assets/js/4f59166d.90f1a358.js index 4c1cdcc7ee..3916c0f50e 100644 --- a/assets/js/4f59166d.ca2e7dd1.js +++ b/assets/js/4f59166d.90f1a358.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3567],{3073:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-6.1/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-6.1/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/annotations-reference.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3567],{3073:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-6.1/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-6.1/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/annotations-reference.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f6c3156.12ca5576.js b/assets/js/4f6c3156.db0f9c03.js similarity index 99% rename from assets/js/4f6c3156.12ca5576.js rename to assets/js/4f6c3156.db0f9c03.js index de3e6a774e..53d4c5ab13 100644 --- a/assets/js/4f6c3156.12ca5576.js +++ b/assets/js/4f6c3156.db0f9c03.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4100],{9810:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>r,contentTitle:()=>o,default:()=>p,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},o=void 0,u={unversionedId:"symfony-bundle-advanced",id:"version-6.1/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/symfony-bundle-advanced.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/laravel-package-advanced"}},r={},s=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:s},m="wrapper";function p(e){let{components:t,...n}=e;return(0,i.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,i.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.kt)("p",null,"By settings ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,i.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.kt)("p",null,"The mutation below will log-in a user:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.kt)("p",null,"In Symfony, user objects implement ",(0,i.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.kt)("p",null,"If you want to get more fields, just add the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")),(0,i.kt)("p",null,"You can now query this field using an ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4100],{9810:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>r,contentTitle:()=>o,default:()=>p,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},o=void 0,u={unversionedId:"symfony-bundle-advanced",id:"version-6.1/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/symfony-bundle-advanced.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/laravel-package-advanced"}},r={},s=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:s},m="wrapper";function p(e){let{components:t,...n}=e;return(0,i.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,i.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.kt)("p",null,"By settings ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,i.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.kt)("p",null,"The mutation below will log-in a user:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.kt)("p",null,"In Symfony, user objects implement ",(0,i.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.kt)("p",null,"If you want to get more fields, just add the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")),(0,i.kt)("p",null,"You can now query this field using an ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/50122f86.1190b66f.js b/assets/js/50122f86.37ed1b04.js similarity index 98% rename from assets/js/50122f86.1190b66f.js rename to assets/js/50122f86.37ed1b04.js index 9b11814552..1c64ff4feb 100644 --- a/assets/js/50122f86.1190b66f.js +++ b/assets/js/50122f86.37ed1b04.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2521],{1454:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>l,metadata:()=>u,toc:()=>r});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},o=void 0,u={unversionedId:"symfony-bundle-advanced",id:"version-4.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-4.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle-advanced.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.0/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.0/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.0/laravel-package-advanced"}},s={},r=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:r},m="wrapper";function p(e){let{components:t,...n}=e;return(0,i.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,i.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.kt)("p",null,"By settings ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,i.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.kt)("p",null,"The mutation below will log-in a user:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.kt)("p",null,"In Symfony, user objects implement ",(0,i.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.kt)("p",null,"If you want to get more fields, just add the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")),(0,i.kt)("p",null,"You can now query this field using an ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2521],{1454:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>l,metadata:()=>u,toc:()=>r});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},o=void 0,u={unversionedId:"symfony-bundle-advanced",id:"version-4.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-4.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle-advanced.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.0/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.0/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.0/laravel-package-advanced"}},s={},r=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:r},m="wrapper";function p(e){let{components:t,...n}=e;return(0,i.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,i.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.kt)("p",null,"By settings ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,i.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.kt)("p",null,"The mutation below will log-in a user:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.kt)("p",null,"In Symfony, user objects implement ",(0,i.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.kt)("p",null,"If you want to get more fields, just add the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")),(0,i.kt)("p",null,"You can now query this field using an ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/504e6c2d.ef45043a.js b/assets/js/504e6c2d.baf50a06.js similarity index 98% rename from assets/js/504e6c2d.ef45043a.js rename to assets/js/504e6c2d.baf50a06.js index 2cf510173a..dafb3181f5 100644 --- a/assets/js/504e6c2d.ef45043a.js +++ b/assets/js/504e6c2d.baf50a06.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8123],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6631:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-6.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-6.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/6.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/file-uploads.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/6.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/6.0/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8123],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6631:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-6.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-6.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/6.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/file-uploads.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/6.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/6.0/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/509d2004.1e0ef8f6.js b/assets/js/509d2004.3c2b48e1.js similarity index 98% rename from assets/js/509d2004.1e0ef8f6.js rename to assets/js/509d2004.3c2b48e1.js index 5146fbbb4d..9d656e82c6 100644 --- a/assets/js/509d2004.1e0ef8f6.js +++ b/assets/js/509d2004.3c2b48e1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1627],{7165:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-5.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/5.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/argument-resolving.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-5.0/docs",previous:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1627],{7165:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-5.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/5.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/argument-resolving.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-5.0/docs",previous:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/528fe65e.0256e3c1.js b/assets/js/528fe65e.3280ecb1.js similarity index 99% rename from assets/js/528fe65e.0256e3c1.js rename to assets/js/528fe65e.3280ecb1.js index 0561bd3a46..77054b9725 100644 --- a/assets/js/528fe65e.0256e3c1.js +++ b/assets/js/528fe65e.3280ecb1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5325],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),s=t(6550),u=t(1980),i=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,i.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,u._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[u,i]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=u??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),i(e),y(e)}),[i,y,l]),tabValues:l}}var g=t(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:n,block:t,selectedValue:s,selectValue:u,tabValues:i}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=i[t].value;a!==s&&(c(n),u(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},i.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",k.tabItem,r?.className,{"tabs__item--active":s===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},p.createElement(f,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},1865:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>u,default:()=>h,frontMatter:()=>s,metadata:()=>i,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},u=void 0,i={unversionedId:"type-mapping",id:"type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/docs/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/next/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/type-mapping.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/next/mutations"},next:{title:"Autowiring services",permalink:"/docs/next/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/next/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/next/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\npublic function companyOrContact(int $id): Company|Contact\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,p.kt)("p",null,(0,p.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5325],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),s=t(6550),u=t(1980),i=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,i.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,u._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[u,i]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=u??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),i(e),y(e)}),[i,y,l]),tabValues:l}}var g=t(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:n,block:t,selectedValue:s,selectValue:u,tabValues:i}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=i[t].value;a!==s&&(c(n),u(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},i.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",k.tabItem,r?.className,{"tabs__item--active":s===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},p.createElement(f,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},1865:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>u,default:()=>h,frontMatter:()=>s,metadata:()=>i,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},u=void 0,i={unversionedId:"type-mapping",id:"type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/docs/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/next/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/type-mapping.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/next/mutations"},next:{title:"Autowiring services",permalink:"/docs/next/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/next/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/next/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\npublic function companyOrContact(int $id): Company|Contact\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,p.kt)("p",null,(0,p.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/54c144e4.1036bcef.js b/assets/js/54c144e4.c2279d68.js similarity index 96% rename from assets/js/54c144e4.1036bcef.js rename to assets/js/54c144e4.c2279d68.js index 6c7e4dda53..0be1c22832 100644 --- a/assets/js/54c144e4.1036bcef.js +++ b/assets/js/54c144e4.c2279d68.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[473],{867:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-4.0/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-4.0/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/4.0/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/inheritance.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"}},c={},o=[],p={toc:o},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[473],{867:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"},s=void 0,l={unversionedId:"inheritance",id:"version-4.0/inheritance",title:"Inheritance and interfaces",description:"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces.",source:"@site/versioned_docs/version-4.0/inheritance.md",sourceDirName:".",slug:"/inheritance",permalink:"/docs/4.0/inheritance",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/inheritance.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance"}},c={},o=[],p={toc:o},d="wrapper";function h(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.kt)("br",null),"GraphQLite automatically declares interfaces when it sees an inheritance relationship between to classes that are GraphQL types."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/54ca8693.d25d41a5.js b/assets/js/54ca8693.ca7ee31a.js similarity index 97% rename from assets/js/54ca8693.d25d41a5.js rename to assets/js/54ca8693.ca7ee31a.js index cc465c51a7..b7ae7f638f 100644 --- a/assets/js/54ca8693.d25d41a5.js +++ b/assets/js/54ca8693.ca7ee31a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9506],{1962:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},i=void 0,o={unversionedId:"symfony-bundle",id:"version-3.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x.",source:"@site/versioned_docs/version-3.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/3.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-3.0/docs",previous:{title:"Getting Started",permalink:"/docs/3.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/3.0/laravel-package"}},s={},p=[{value:"Installation",id:"installation",level:2}],d={toc:p},u="wrapper";function c(e){let{components:t,...n}=e;return(0,r.kt)(u,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"The Symfony Flex recipe is not yet available."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},i=void 0,o={unversionedId:"symfony-bundle",id:"version-3.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x.",source:"@site/versioned_docs/version-3.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/3.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-3.0/docs",previous:{title:"Getting Started",permalink:"/docs/3.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/3.0/laravel-package"}},s={},p=[{value:"Installation",id:"installation",level:2}],d={toc:p},u="wrapper";function c(e){let{components:t,...n}=e;return(0,r.kt)(u,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"The Symfony Flex recipe is not yet available."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-4.2/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-4.2/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.2/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/semver.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-4.2/docs",previous:{title:"Annotations reference",permalink:"/docs/4.2/annotations-reference"},next:{title:"Changelog",permalink:"/docs/4.2/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6463],{9941:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-4.2/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-4.2/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.2/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/semver.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-4.2/docs",previous:{title:"Annotations reference",permalink:"/docs/4.2/annotations-reference"},next:{title:"Changelog",permalink:"/docs/4.2/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/56279b5e.681e0b3f.js b/assets/js/56279b5e.30fed670.js similarity index 99% rename from assets/js/56279b5e.681e0b3f.js rename to assets/js/56279b5e.30fed670.js index ca85578a16..d0ba19906d 100644 --- a/assets/js/56279b5e.681e0b3f.js +++ b/assets/js/56279b5e.30fed670.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8584],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},1597:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-4.2/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.2/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.2/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/input-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-4.2/docs",previous:{title:"External type declaration",permalink:"/docs/4.2/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8584],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},1597:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-4.2/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.2/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.2/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/input-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-4.2/docs",previous:{title:"External type declaration",permalink:"/docs/4.2/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/565a5567.bc14bb1d.js b/assets/js/565a5567.88632e57.js similarity index 98% rename from assets/js/565a5567.bc14bb1d.js rename to assets/js/565a5567.88632e57.js index 42b30d9572..26590e2f66 100644 --- a/assets/js/565a5567.bc14bb1d.js +++ b/assets/js/565a5567.88632e57.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9137],{2887:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/doctrine_annotations_attributes.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9137],{2887:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/doctrine_annotations_attributes.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/56af72f6.9aa66707.js b/assets/js/56af72f6.c4e69c59.js similarity index 99% rename from assets/js/56af72f6.9aa66707.js rename to assets/js/56af72f6.c4e69c59.js index e8478c7ac9..e8afe3e4f3 100644 --- a/assets/js/56af72f6.9aa66707.js +++ b/assets/js/56af72f6.c4e69c59.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6317],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},2896:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-6.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-6.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/6.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/custom-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/6.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6317],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},2896:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-6.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-6.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/6.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/custom-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/6.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5792f9ba.1f9fbaa4.js b/assets/js/5792f9ba.7f08dd0b.js similarity index 98% rename from assets/js/5792f9ba.1f9fbaa4.js rename to assets/js/5792f9ba.7f08dd0b.js index b115184fd2..99c15ef84e 100644 --- a/assets/js/5792f9ba.1f9fbaa4.js +++ b/assets/js/5792f9ba.7f08dd0b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5259],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2976:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},s=void 0,u={unversionedId:"autowiring",id:"version-4.1/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.1/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.1/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/autowiring.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.1/docs",previous:{title:"Type mapping",permalink:"/docs/4.1/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.1/extend_type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5259],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2976:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},s=void 0,u={unversionedId:"autowiring",id:"version-4.1/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.1/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.1/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/autowiring.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.1/docs",previous:{title:"Type mapping",permalink:"/docs/4.1/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.1/extend_type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/579cc8d4.fbcdc4ed.js b/assets/js/579cc8d4.c024d536.js similarity index 98% rename from assets/js/579cc8d4.fbcdc4ed.js rename to assets/js/579cc8d4.c024d536.js index 6b9a54b684..ea63771ce1 100644 --- a/assets/js/579cc8d4.fbcdc4ed.js +++ b/assets/js/579cc8d4.c024d536.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2037],{1529:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-3.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-3.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/3.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/implementing-security.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"}},u={},c=[],l={toc:c},h="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2037],{1529:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-3.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-3.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/3.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/implementing-security.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"}},u={},c=[],l={toc:c},h="wrapper";function p(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/57f5c28c.df5990bb.js b/assets/js/57f5c28c.3f0e7ab5.js similarity index 99% rename from assets/js/57f5c28c.df5990bb.js rename to assets/js/57f5c28c.3f0e7ab5.js index acedba88bd..acc860e5cd 100644 --- a/assets/js/57f5c28c.df5990bb.js +++ b/assets/js/57f5c28c.3f0e7ab5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5138],{8314:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=t(7462),r=(t(7294),t(3905));t(1839);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,l={unversionedId:"other-frameworks",id:"version-4.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/other_frameworks.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.0/docs",previous:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],c={toc:p},d="wrapper";function u(e){let{components:n,...o}=e;return(0,r.kt)(d,(0,a.Z)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If you are using ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony bundle"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"composer.json")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"index.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,r.kt)("p",null,(0,r.kt)("img",{src:t(1410).Z,width:"1132",height:"352"})))}u.isMDXComponent=!0},1410:(e,n,t)=>{t.d(n,{Z:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5138],{8314:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=t(7462),r=(t(7294),t(3905));t(1839);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,l={unversionedId:"other-frameworks",id:"version-4.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/other_frameworks.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.0/docs",previous:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],c={toc:p},d="wrapper";function u(e){let{components:n,...o}=e;return(0,r.kt)(d,(0,a.Z)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If you are using ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony bundle"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"composer.json")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"index.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,r.kt)("p",null,(0,r.kt)("img",{src:t(1410).Z,width:"1132",height:"352"})))}u.isMDXComponent=!0},1410:(e,n,t)=>{t.d(n,{Z:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/58d52345.8cf47ddc.js b/assets/js/58d52345.1410724b.js similarity index 95% rename from assets/js/58d52345.8cf47ddc.js rename to assets/js/58d52345.1410724b.js index a16b1b9c4b..9fda085916 100644 --- a/assets/js/58d52345.8cf47ddc.js +++ b/assets/js/58d52345.1410724b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2446],{6297:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>d});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},l=void 0,s={unversionedId:"features",id:"version-4.0/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.0/features.md",sourceDirName:".",slug:"/",permalink:"/docs/4.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/features.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.0/docs",next:{title:"Getting Started",permalink:"/docs/4.0/getting-started"}},o={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],u={toc:d},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(p,(0,r.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2446],{6297:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>d});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},l=void 0,s={unversionedId:"features",id:"version-4.0/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.0/features.md",sourceDirName:".",slug:"/",permalink:"/docs/4.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/features.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.0/docs",next:{title:"Getting Started",permalink:"/docs/4.0/getting-started"}},o={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],u={toc:d},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(p,(0,r.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/58e6b30f.796c7df7.js b/assets/js/58e6b30f.448b537c.js similarity index 98% rename from assets/js/58e6b30f.796c7df7.js rename to assets/js/58e6b30f.448b537c.js index d61ec48a17..65282786ec 100644 --- a/assets/js/58e6b30f.796c7df7.js +++ b/assets/js/58e6b30f.448b537c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1326],{8941:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},l=void 0,r={unversionedId:"external_type_declaration",id:"version-3.0/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-3.0/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/3.0/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/external_type_declaration.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-3.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/3.0/authentication_authorization"},next:{title:"Input types",permalink:"/docs/3.0/input-types"}},s={},d=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],p={toc:d},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,i.kt)("li",{parentName:"ul"},"etc.")),(0,i.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.kt)("p",null,"GraphQLite allows you to use a ",(0,i.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("p",null,"In methods with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotaiton, the first parameter is the ",(0,i.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.kt)("h2",{id:"sourcefield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.kt)("p",null,"If you don't want to rewrite all ",(0,i.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')),(0,i.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.kt)("p",null,"You may also check for logged users or users with a specific right using the ",(0,i.kt)("inlineCode",{parentName:"p"},"logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"right")," properties of the annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", logged=true, right=@Right(name="CAN_ACCESS_Price"))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.kt)("p",null,"Just like the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations for regular fields, you can define a default value to use\nin case the user has insufficient permissions:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @SourceField(name="status", logged=true, right=@Right(name="CAN_ACCESS_STATUS"), failWith=null)\n */\n')),(0,i.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1326],{8941:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},l=void 0,r={unversionedId:"external_type_declaration",id:"version-3.0/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-3.0/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/3.0/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/external_type_declaration.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-3.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/3.0/authentication_authorization"},next:{title:"Input types",permalink:"/docs/3.0/input-types"}},s={},d=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],p={toc:d},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,i.kt)("li",{parentName:"ul"},"etc.")),(0,i.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.kt)("p",null,"GraphQLite allows you to use a ",(0,i.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("p",null,"In methods with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotaiton, the first parameter is the ",(0,i.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.kt)("h2",{id:"sourcefield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.kt)("p",null,"If you don't want to rewrite all ",(0,i.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')),(0,i.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.kt)("p",null,"You may also check for logged users or users with a specific right using the ",(0,i.kt)("inlineCode",{parentName:"p"},"logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"right")," properties of the annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", logged=true, right=@Right(name="CAN_ACCESS_Price"))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.kt)("p",null,"Just like the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations for regular fields, you can define a default value to use\nin case the user has insufficient permissions:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @SourceField(name="status", logged=true, right=@Right(name="CAN_ACCESS_STATUS"), failWith=null)\n */\n')),(0,i.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5945e8b0.419e3a48.js b/assets/js/5945e8b0.b16e6f0b.js similarity index 99% rename from assets/js/5945e8b0.419e3a48.js rename to assets/js/5945e8b0.b16e6f0b.js index b6b2ee8bfb..a62a59d870 100644 --- a/assets/js/5945e8b0.419e3a48.js +++ b/assets/js/5945e8b0.b16e6f0b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4584],{5581:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-6.0/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/6.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/symfony-bundle.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/6.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/6.0/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-6.0/symfony-bundle",title:"Getting started with Symfony",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/6.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/symfony-bundle.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/6.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/6.0/laravel-package"}},s={},p=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:p},d="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,i.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,i.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Now, go to the ",(0,i.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-yaml",metastring:'title="config/packages/graphqlite.yaml"',title:'"config/packages/graphqlite.yaml"'},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,i.kt)("p",null,"More advanced parameters are detailed in the ",(0,i.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[p,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},2075:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/docs/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/next/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/README.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/next/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[67],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[p,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},2075:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/docs/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/next/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/README.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/next/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5a9b411c.21031480.js b/assets/js/5a9b411c.b408216a.js similarity index 99% rename from assets/js/5a9b411c.21031480.js rename to assets/js/5a9b411c.b408216a.js index ccc4669703..164655f143 100644 --- a/assets/js/5a9b411c.21031480.js +++ b/assets/js/5a9b411c.b408216a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7336],{7890:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const o={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},l=void 0,i={unversionedId:"laravel-package",id:"version-4.0/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.7+ and Laravel 6.x.",source:"@site/versioned_docs/version-4.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/laravel-package.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-4.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:a,...t}=e;return(0,r.kt)(d,(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7336],{7890:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const o={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},l=void 0,i={unversionedId:"laravel-package",id:"version-4.0/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.7+ and Laravel 6.x.",source:"@site/versioned_docs/version-4.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/laravel-package.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-4.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:a,...t}=e;return(0,r.kt)(d,(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5d7590c2.8e1fd956.js b/assets/js/5d7590c2.a13f01b9.js similarity index 99% rename from assets/js/5d7590c2.8e1fd956.js rename to assets/js/5d7590c2.a13f01b9.js index 3ef5c5b9a3..a7a5b395f4 100644 --- a/assets/js/5d7590c2.8e1fd956.js +++ b/assets/js/5d7590c2.a13f01b9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1571],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5640:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/docs/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/next/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/pagination.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/next/file-uploads"},next:{title:"Custom types",permalink:"/docs/next/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1571],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5640:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/docs/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/next/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/pagination.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/next/file-uploads"},next:{title:"Custom types",permalink:"/docs/next/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5e21a9be.98348313.js b/assets/js/5e21a9be.9d203747.js similarity index 99% rename from assets/js/5e21a9be.98348313.js rename to assets/js/5e21a9be.9d203747.js index 5a9ab44c85..3b4be47101 100644 --- a/assets/js/5e21a9be.98348313.js +++ b/assets/js/5e21a9be.9d203747.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[905],{7002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.2/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.2/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/laravel-package.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-4.2/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.2/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[905],{7002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.2/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.2/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/laravel-package.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-4.2/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.2/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5e352ef4.9b70e54f.js b/assets/js/5e352ef4.0e87aed3.js similarity index 99% rename from assets/js/5e352ef4.9b70e54f.js rename to assets/js/5e352ef4.0e87aed3.js index de807896c4..1ab83d7b8a 100644 --- a/assets/js/5e352ef4.9b70e54f.js +++ b/assets/js/5e352ef4.0e87aed3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7925],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},1975:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-3.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-3.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/3.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/validation.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7925],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},1975:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-3.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-3.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/3.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/validation.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5ec7a7fe.04316e40.js b/assets/js/5ec7a7fe.a1f7d0fb.js similarity index 99% rename from assets/js/5ec7a7fe.04316e40.js rename to assets/js/5ec7a7fe.a1f7d0fb.js index 43686bd65b..72580958e7 100644 --- a/assets/js/5ec7a7fe.04316e40.js +++ b/assets/js/5ec7a7fe.a1f7d0fb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1905],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9598:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-6.0/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-6.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/6.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/extend-type.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/6.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/6.0/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1905],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9598:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-6.0/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-6.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/6.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/extend-type.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/6.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/6.0/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5ececfab.2c36e31a.js b/assets/js/5ececfab.f2968018.js similarity index 99% rename from assets/js/5ececfab.2c36e31a.js rename to assets/js/5ececfab.f2968018.js index 1ca8185f77..82789f0894 100644 --- a/assets/js/5ececfab.2c36e31a.js +++ b/assets/js/5ececfab.f2968018.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3173],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},5199:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-4.3/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.3/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/4.3/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/type-mapping.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-4.3/docs",previous:{title:"Mutations",permalink:"/docs/4.3/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.3/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.3/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.3/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3173],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},5199:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-4.3/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.3/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/4.3/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/type-mapping.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-4.3/docs",previous:{title:"Mutations",permalink:"/docs/4.3/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.3/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.3/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.3/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5fa4a5b6.efc20e96.js b/assets/js/5fa4a5b6.9fc9d71c.js similarity index 99% rename from assets/js/5fa4a5b6.efc20e96.js rename to assets/js/5fa4a5b6.9fc9d71c.js index 1c07bad14b..0245891bcb 100644 --- a/assets/js/5fa4a5b6.efc20e96.js +++ b/assets/js/5fa4a5b6.9fc9d71c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3312],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),y=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var y=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",f.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,y.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7694:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.1/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-4.1/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.1/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle-advanced.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.1/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3312],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),y=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var y=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",f.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,y.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7694:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.1/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-4.1/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.1/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle-advanced.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.1/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5ffc8074.ba853ab9.js b/assets/js/5ffc8074.034c05bc.js similarity index 99% rename from assets/js/5ffc8074.ba853ab9.js rename to assets/js/5ffc8074.034c05bc.js index 86ab9f8a98..7a8a58fe28 100644 --- a/assets/js/5ffc8074.ba853ab9.js +++ b/assets/js/5ffc8074.034c05bc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7959],{1474:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(7462),l=(n(7294),n(3905));n(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-3.0/annotations_reference",title:"Annotations reference",description:"@Query annotation",source:"@site/versioned_docs/version-3.0/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/3.0/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/annotations_reference.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-3.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/3.0/troubleshooting"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...n}=t;return(0,l.kt)(u,(0,a.Z)({},m,n,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"logged"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether the user must be logged or not to see the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"right"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"Right annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"The right the user must have to see the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"failWith"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"A value to return if the user is not authorized to see the field. If not specified, the field will not be visible at all to the user.")))),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7959],{1474:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(7462),l=(n(7294),n(3905));n(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-3.0/annotations_reference",title:"Annotations reference",description:"@Query annotation",source:"@site/versioned_docs/version-3.0/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/3.0/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/annotations_reference.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-3.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/3.0/troubleshooting"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...n}=t;return(0,l.kt)(u,(0,a.Z)({},m,n,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"logged"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether the user must be logged or not to see the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"right"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"Right annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"The right the user must have to see the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"failWith"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"A value to return if the user is not authorized to see the field. If not specified, the field will not be visible at all to the user.")))),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/606959d6.d3f9b660.js b/assets/js/606959d6.c1125b7a.js similarity index 99% rename from assets/js/606959d6.d3f9b660.js rename to assets/js/606959d6.c1125b7a.js index 6eb6acd6a1..09db351b60 100644 --- a/assets/js/606959d6.d3f9b660.js +++ b/assets/js/606959d6.c1125b7a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2272],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3419:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.2/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.2/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/laravel-package-advanced.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-4.2/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.2/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2272],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3419:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.2/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.2/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.2/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/laravel-package-advanced.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-4.2/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.2/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/60d99771.c95dbd1c.js b/assets/js/60d99771.4901986b.js similarity index 98% rename from assets/js/60d99771.c95dbd1c.js rename to assets/js/60d99771.4901986b.js index e22a01c173..6817aeba46 100644 --- a/assets/js/60d99771.c95dbd1c.js +++ b/assets/js/60d99771.4901986b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7121],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9557:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-5.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-5.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/5.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/query-plan.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-5.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/5.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/5.0/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7121],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9557:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-5.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-5.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/5.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/query-plan.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-5.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/5.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/5.0/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/610e7425.edff6221.js b/assets/js/610e7425.cf6abf89.js similarity index 98% rename from assets/js/610e7425.edff6221.js rename to assets/js/610e7425.cf6abf89.js index 18c971808f..b340a2c561 100644 --- a/assets/js/610e7425.edff6221.js +++ b/assets/js/610e7425.cf6abf89.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6409],{1772:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(7462),i=(t(7294),t(3905));t(1839);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-6.1/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-6.1/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/inheritance-interfaces.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/input-types"},next:{title:"Error handling",permalink:"/docs/error-handling"}},p={},c=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],o={toc:c},d="wrapper";function m(e){let{components:n,...t}=e;return(0,i.kt)(d,(0,a.Z)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will translate in GraphQL schema as:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.kt)("p",null,"Please note that you do not need to put the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.kt)("p",null,"You don't have to explicitly put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")),(0,i.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,i.kt)("p",null,"In the example above, because the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6409],{1772:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(7462),i=(t(7294),t(3905));t(1839);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-6.1/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-6.1/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/inheritance-interfaces.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/input-types"},next:{title:"Error handling",permalink:"/docs/error-handling"}},p={},c=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],o={toc:c},d="wrapper";function m(e){let{components:n,...t}=e;return(0,i.kt)(d,(0,a.Z)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will translate in GraphQL schema as:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.kt)("p",null,"Please note that you do not need to put the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.kt)("p",null,"You don't have to explicitly put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")),(0,i.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,i.kt)("p",null,"In the example above, because the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/612b773e.08c521a0.js b/assets/js/612b773e.d0b59610.js similarity index 99% rename from assets/js/612b773e.08c521a0.js rename to assets/js/612b773e.d0b59610.js index 670da51da4..bf645919f1 100644 --- a/assets/js/612b773e.08c521a0.js +++ b/assets/js/612b773e.d0b59610.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2415],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const u={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(u.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),u=a(6010),o=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(u),(0,r.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:u})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,u]),tabValues:u}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},o,{className:(0,u.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,u.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6687:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),u=(a(1839),a(4866)),o=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/docs/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/next/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/mutations.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/next/queries"},next:{title:"Type mapping",permalink:"/docs/next/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2415],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const u={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(u.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),u=a(6010),o=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(u),(0,r.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:u})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,u]),tabValues:u}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},o,{className:(0,u.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,u.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6687:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),u=(a(1839),a(4866)),o=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/docs/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/next/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/mutations.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/next/queries"},next:{title:"Type mapping",permalink:"/docs/next/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/61595218.81593eed.js b/assets/js/61595218.0e14427c.js similarity index 99% rename from assets/js/61595218.81593eed.js rename to assets/js/61595218.0e14427c.js index d8a43d3bab..09f4420345 100644 --- a/assets/js/61595218.81593eed.js +++ b/assets/js/61595218.0e14427c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[529],{8968:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-4.2/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.2/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/4.2/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/annotations-reference.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-4.2/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.2/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.2/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[529],{8968:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-4.2/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.2/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/4.2/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/annotations-reference.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-4.2/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.2/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.2/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.2/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.2/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/617523b3.ffbea4c0.js b/assets/js/617523b3.fdc3aa9c.js similarity index 99% rename from assets/js/617523b3.ffbea4c0.js rename to assets/js/617523b3.fdc3aa9c.js index f5a05e8c78..d8b730e352 100644 --- a/assets/js/617523b3.ffbea4c0.js +++ b/assets/js/617523b3.fdc3aa9c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8752],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),p=a(1980),o=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,p._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[p,o]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=p??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),o(e),f(e)}),[o,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},o.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},6733:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.1/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.1/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/multiple_output_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},sidebar:"version-4.1/docs",previous:{title:"Extending an input type",permalink:"/docs/4.1/extend_input_type"},next:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/external_type_declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8752],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),p=a(1980),o=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,p._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[p,o]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=p??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),o(e),f(e)}),[o,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},o.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},6733:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.1/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.1/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/multiple_output_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},sidebar:"version-4.1/docs",previous:{title:"Extending an input type",permalink:"/docs/4.1/extend_input_type"},next:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/external_type_declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/61c7d915.8b573ca5.js b/assets/js/61c7d915.398ed930.js similarity index 96% rename from assets/js/61c7d915.8b573ca5.js rename to assets/js/61c7d915.398ed930.js index 62d1175010..04d41b0e83 100644 --- a/assets/js/61c7d915.8b573ca5.js +++ b/assets/js/61c7d915.398ed930.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1506],{4751:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},l=void 0,i={unversionedId:"query-plan",id:"version-6.1/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-6.1/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/query-plan.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/prefetch-method"}},s={},u=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1506],{4751:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},l=void 0,i={unversionedId:"query-plan",id:"version-6.1/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-6.1/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/query-plan.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/prefetch-method"}},s={},u=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/623b6c78.87ac2c9d.js b/assets/js/623b6c78.1c316b9c.js similarity index 99% rename from assets/js/623b6c78.87ac2c9d.js rename to assets/js/623b6c78.1c316b9c.js index 0062d54ee7..3cce095dba 100644 --- a/assets/js/623b6c78.87ac2c9d.js +++ b/assets/js/623b6c78.1c316b9c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2080],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},o,{className:(0,s.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},5845:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),o=n(5162);const l={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.1/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.1/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.1/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/prefetch_method.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},sidebar:"version-4.1/docs",previous:{title:"Query plan",permalink:"/docs/4.1/query-plan"},next:{title:"File uploads",permalink:"/docs/4.1/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2080],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},o,{className:(0,s.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},5845:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),o=n(5162);const l={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.1/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.1/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.1/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/prefetch_method.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records",original_id:"prefetch-method"},sidebar:"version-4.1/docs",previous:{title:"Query plan",permalink:"/docs/4.1/query-plan"},next:{title:"File uploads",permalink:"/docs/4.1/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/64536e1a.4db27fae.js b/assets/js/64536e1a.aab3dff8.js similarity index 98% rename from assets/js/64536e1a.4db27fae.js rename to assets/js/64536e1a.aab3dff8.js index 41c5bd2fab..4cf5ad91eb 100644 --- a/assets/js/64536e1a.4db27fae.js +++ b/assets/js/64536e1a.aab3dff8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6561],{8685:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/docs/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/next/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/operation-complexity.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/next/implementing-security"},next:{title:"Query plan",permalink:"/docs/next/query-plan"}},p={},s=[{value:"Query depth",id:"query-depth",level:2},{value:"Static request analysis",id:"static-request-analysis",level:2},{value:"Full request analysis",id:"full-request-analysis",level:2},{value:"Setup",id:"setup",level:2}],u={toc:s},h="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(h,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"At some point you may find yourself receiving queries with an insane amount of requested\nfields or items, all at once. Usually, it's not a good thing, so you may want to somehow\nlimit the amount of requests or their individual complexity. "),(0,i.kt)("h2",{id:"query-depth"},"Query depth"),(0,i.kt)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/security/#limiting-query-depth"},"has this built in"),".\nTo use it, you may use ",(0,i.kt)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.kt)("p",null,"Although this works for simple cases, this doesn't prevent requesting an excessive amount\nof fields on the depth of under 7, nor does it prevent requesting too many nodes in paginated lists.\nThis is where automatic query complexity comes to save us."),(0,i.kt)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.kt)("p",null,"The operation complexity analyzer is a useful tool to make your API secure. The operation\ncomplexity analyzer assigns by default every field a complexity of ",(0,i.kt)("inlineCode",{parentName:"p"},"1"),". The complexity of\nall fields in one of the operations of a GraphQL request is not allowed to be greater\nthan the maximum permitted operation complexity."),(0,i.kt)("p",null,"This sounds fairly simple at first, but the more you think about this, the more you\nwonder if that is so. Does every field have the same complexity?"),(0,i.kt)("p",null,"In a data graph, not every field is the same. We have fields that fetch data that are\nmore expensive than fields that just complete already resolved data."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"type Query {\n books(take: Int = 10): [Book]\n}\n\ntype Book {\n title\n author: Author\n}\n\ntype Author {\n name\n}\n")),(0,i.kt)("p",null,"In the above example executing the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.kt)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.kt)("inlineCode",{parentName:"p"},"title")," field. The cost of the title field\nmight be the impact on the memory and to the transport. For ",(0,i.kt)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.kt)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.kt)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.kt)("p",null,"Moreover, we have the field ",(0,i.kt)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class Controller {\n /**\n * @return Book[]\n */\n #[Query]\n #[Cost(complexity: 10)]\n public function books(int $take = 10): array {}\n}\n\n#[Type]\nclass Book {\n #[Field]\n public string $title;\n \n #[Field]\n #[Cost(complexity: 5)]\n public Author $author;\n}\n\n#[Type]\nclass Author {\n #[Field]\n public string $name;\n}\n")),(0,i.kt)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"11"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.kt)("p",null,"When drilling in further, a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("p",null,"This kind of analysis is entirely static and could just be done by inspecting the\nquery syntax tree. The impact on the overall execution performance is very low.\nBut with this static approach, we do have a very rough idea of the performance.\nIs it correct to apply always a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.kt)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.kt)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.kt)("p",null,"If we look at our data graph, we can see that the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.kt)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.kt)("inlineCode",{parentName:"p"},"5")," since now we\nget a more fine-grained cost calculation by multiplying the complexity\nof the field with the ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class Controller {\n /**\n * @return Book[]\n */\n #[Query]\n #[Cost(complexity: 5, multipliers: ['take'], defaultMultiplier: 200)]\n public function books(?int $take = 10): array {}\n}\n\n#[Type]\nclass Book {\n #[Field]\n public string $title;\n \n #[Field]\n #[Cost(complexity: 5)]\n public Author $author;\n}\n\n#[Type]\nclass Author {\n #[Field]\n public string $name;\n}\n")),(0,i.kt)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"60")," for the request since the multiplier\nis applied to the books field and the child fields' cost. If multiple multipliers are specified,\nthe cost will be multiplied by each of the fields."),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.kt)("p",null,"When drilling in further, the cost will go up to ",(0,i.kt)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("p",null,"Notice the nullable ",(0,i.kt)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.kt)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.kt)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.kt)("p",null,"If all of the multiplier fields are either ",(0,i.kt)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.kt)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("h2",{id:"setup"},"Setup"),(0,i.kt)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n// Total query cost cannot exceed 1000 points\n$builder->limitQueryComplexity(1000);\n")),(0,i.kt)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.kt)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.kt)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6561],{8685:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/docs/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/next/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/operation-complexity.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/next/implementing-security"},next:{title:"Query plan",permalink:"/docs/next/query-plan"}},p={},s=[{value:"Query depth",id:"query-depth",level:2},{value:"Static request analysis",id:"static-request-analysis",level:2},{value:"Full request analysis",id:"full-request-analysis",level:2},{value:"Setup",id:"setup",level:2}],u={toc:s},h="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(h,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"At some point you may find yourself receiving queries with an insane amount of requested\nfields or items, all at once. Usually, it's not a good thing, so you may want to somehow\nlimit the amount of requests or their individual complexity. "),(0,i.kt)("h2",{id:"query-depth"},"Query depth"),(0,i.kt)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/security/#limiting-query-depth"},"has this built in"),".\nTo use it, you may use ",(0,i.kt)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.kt)("p",null,"Although this works for simple cases, this doesn't prevent requesting an excessive amount\nof fields on the depth of under 7, nor does it prevent requesting too many nodes in paginated lists.\nThis is where automatic query complexity comes to save us."),(0,i.kt)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.kt)("p",null,"The operation complexity analyzer is a useful tool to make your API secure. The operation\ncomplexity analyzer assigns by default every field a complexity of ",(0,i.kt)("inlineCode",{parentName:"p"},"1"),". The complexity of\nall fields in one of the operations of a GraphQL request is not allowed to be greater\nthan the maximum permitted operation complexity."),(0,i.kt)("p",null,"This sounds fairly simple at first, but the more you think about this, the more you\nwonder if that is so. Does every field have the same complexity?"),(0,i.kt)("p",null,"In a data graph, not every field is the same. We have fields that fetch data that are\nmore expensive than fields that just complete already resolved data."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"type Query {\n books(take: Int = 10): [Book]\n}\n\ntype Book {\n title\n author: Author\n}\n\ntype Author {\n name\n}\n")),(0,i.kt)("p",null,"In the above example executing the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.kt)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.kt)("inlineCode",{parentName:"p"},"title")," field. The cost of the title field\nmight be the impact on the memory and to the transport. For ",(0,i.kt)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.kt)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.kt)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.kt)("p",null,"Moreover, we have the field ",(0,i.kt)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class Controller {\n /**\n * @return Book[]\n */\n #[Query]\n #[Cost(complexity: 10)]\n public function books(int $take = 10): array {}\n}\n\n#[Type]\nclass Book {\n #[Field]\n public string $title;\n \n #[Field]\n #[Cost(complexity: 5)]\n public Author $author;\n}\n\n#[Type]\nclass Author {\n #[Field]\n public string $name;\n}\n")),(0,i.kt)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"11"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.kt)("p",null,"When drilling in further, a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("p",null,"This kind of analysis is entirely static and could just be done by inspecting the\nquery syntax tree. The impact on the overall execution performance is very low.\nBut with this static approach, we do have a very rough idea of the performance.\nIs it correct to apply always a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.kt)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.kt)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.kt)("p",null,"If we look at our data graph, we can see that the ",(0,i.kt)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.kt)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.kt)("inlineCode",{parentName:"p"},"5")," since now we\nget a more fine-grained cost calculation by multiplying the complexity\nof the field with the ",(0,i.kt)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class Controller {\n /**\n * @return Book[]\n */\n #[Query]\n #[Cost(complexity: 5, multipliers: ['take'], defaultMultiplier: 200)]\n public function books(?int $take = 10): array {}\n}\n\n#[Type]\nclass Book {\n #[Field]\n public string $title;\n \n #[Field]\n #[Cost(complexity: 5)]\n public Author $author;\n}\n\n#[Type]\nclass Author {\n #[Field]\n public string $name;\n}\n")),(0,i.kt)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.kt)("inlineCode",{parentName:"p"},"60")," for the request since the multiplier\nis applied to the books field and the child fields' cost. If multiple multipliers are specified,\nthe cost will be multiplied by each of the fields."),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.kt)("p",null,"When drilling in further, the cost will go up to ",(0,i.kt)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("p",null,"Notice the nullable ",(0,i.kt)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.kt)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.kt)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.kt)("p",null,"If all of the multiplier fields are either ",(0,i.kt)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.kt)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.kt)("p",null,"Cost calculation: ",(0,i.kt)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.kt)("h2",{id:"setup"},"Setup"),(0,i.kt)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n// Total query cost cannot exceed 1000 points\n$builder->limitQueryComplexity(1000);\n")),(0,i.kt)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.kt)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.kt)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/64947e00.9d587f96.js b/assets/js/64947e00.45a668db.js similarity index 99% rename from assets/js/64947e00.9d587f96.js rename to assets/js/64947e00.45a668db.js index 389d77e37a..ce18053284 100644 --- a/assets/js/64947e00.9d587f96.js +++ b/assets/js/64947e00.45a668db.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2885],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},76:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-5.0/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-5.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/5.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/input-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-5.0/docs",previous:{title:"External type declaration",permalink:"/docs/5.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2885],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},76:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-5.0/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-5.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/5.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/input-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"version-5.0/docs",previous:{title:"External type declaration",permalink:"/docs/5.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"}},s={},c=[{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3},{value:"@Input Annotation",id:"input-annotation",level:2},{value:"Multiple input types per one class",id:"multiple-input-types-per-one-class",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.kt)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.kt)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.kt)("p",null,"Let's transform ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.kt)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.kt)("p",null,"Simple usage of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates an GraphQl input named by class name + "Input" suffix if a class name does not end with it already.\nYou can add multiple ',(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n #[Field]\n public ?int $age;\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /**\n * @Field()\n * @var int|null\n */\n public $age;\n}\n')))),(0,l.kt)("p",null,"There are 2 input types created for just one class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/652c74f1.311657a5.js b/assets/js/652c74f1.c5d3d2e8.js similarity index 99% rename from assets/js/652c74f1.311657a5.js rename to assets/js/652c74f1.c5d3d2e8.js index 9e18e3f932..e5a12a8272 100644 --- a/assets/js/652c74f1.311657a5.js +++ b/assets/js/652c74f1.c5d3d2e8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8110],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},7682:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-4.3/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.3/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.3/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/queries.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-4.3/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.3/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.3/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8110],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},7682:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-4.3/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.3/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.3/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/queries.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-4.3/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.3/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.3/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/673df5d6.8b8c55e3.js b/assets/js/673df5d6.54464c7c.js similarity index 98% rename from assets/js/673df5d6.8b8c55e3.js rename to assets/js/673df5d6.54464c7c.js index 28679ae032..306187889b 100644 --- a/assets/js/673df5d6.8b8c55e3.js +++ b/assets/js/673df5d6.54464c7c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4060],{2829:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.1/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.7+, Laravel 6.x and Laravel 7.x.",source:"@site/versioned_docs/version-4.1/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.1/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/laravel-package.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-4.1/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.1/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.1/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:a,...t}=e;return(0,r.kt)(d,(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4060],{2829:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.1/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.7+, Laravel 6.x and Laravel 7.x.",source:"@site/versioned_docs/version-4.1/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.1/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/laravel-package.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-4.1/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.1/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.1/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:a,...t}=e;return(0,r.kt)(d,(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/68b7d615.f0c191ec.js b/assets/js/68b7d615.1a23ca24.js similarity index 99% rename from assets/js/68b7d615.f0c191ec.js rename to assets/js/68b7d615.1a23ca24.js index 0de1251698..24821463bc 100644 --- a/assets/js/68b7d615.f0c191ec.js +++ b/assets/js/68b7d615.1a23ca24.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6313],{7037:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-5.0/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-5.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/5.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/annotations-reference.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-5.0/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/5.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/5.0/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6313],{7037:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,o={unversionedId:"annotations-reference",id:"version-5.0/annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-5.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/5.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/annotations-reference.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"version-5.0/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/5.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/5.0/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Input annotation",id:"input-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("em",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation.")))),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/5.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/69f2ab1f.4b6d8226.js b/assets/js/69f2ab1f.269ccd0b.js similarity index 98% rename from assets/js/69f2ab1f.4b6d8226.js rename to assets/js/69f2ab1f.269ccd0b.js index fed8acb6b9..9ea848099e 100644 --- a/assets/js/69f2ab1f.4b6d8226.js +++ b/assets/js/69f2ab1f.269ccd0b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2157],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5380:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-6.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-6.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/6.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/pagination.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/6.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/6.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2157],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5380:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-6.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-6.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/6.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/pagination.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/6.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/6.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6ad31330.e03970f0.js b/assets/js/6ad31330.26f70583.js similarity index 94% rename from assets/js/6ad31330.e03970f0.js rename to assets/js/6ad31330.26f70583.js index 9dab8aea4b..49111b58a4 100644 --- a/assets/js/6ad31330.e03970f0.js +++ b/assets/js/6ad31330.26f70583.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6555],{4975:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-5.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-5.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/5.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/getting-started.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-5.0/docs",previous:{title:"GraphQLite",permalink:"/docs/5.0/"},next:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6555],{4975:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-5.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-5.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/5.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/getting-started.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-5.0/docs",previous:{title:"GraphQLite",permalink:"/docs/5.0/"},next:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c124661.f907a4c2.js b/assets/js/6c124661.4afbc706.js similarity index 98% rename from assets/js/6c124661.f907a4c2.js rename to assets/js/6c124661.4afbc706.js index c22963f659..427141e1ec 100644 --- a/assets/js/6c124661.f907a4c2.js +++ b/assets/js/6c124661.4afbc706.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[742],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(c(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(y,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9152:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/docs/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/next/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/file-uploads.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/next/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/next/pagination"}},p={},c=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[742],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(c(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(y,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9152:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/docs/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/next/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/file-uploads.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/next/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/next/pagination"}},p={},c=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c14a231.c405675e.js b/assets/js/6c14a231.1bf3c0cf.js similarity index 99% rename from assets/js/6c14a231.c405675e.js rename to assets/js/6c14a231.1bf3c0cf.js index c881a998b6..f651f6a2b9 100644 --- a/assets/js/6c14a231.c405675e.js +++ b/assets/js/6c14a231.1bf3c0cf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2835],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9276:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-5.0/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-5.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/5.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/README.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-5.0/docs",next:{title:"Getting Started",permalink:"/docs/5.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2835],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9276:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-5.0/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-5.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/5.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/README.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-5.0/docs",next:{title:"Getting Started",permalink:"/docs/5.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c6ce37c.16a084ae.js b/assets/js/6c6ce37c.18a34ffd.js similarity index 97% rename from assets/js/6c6ce37c.16a084ae.js rename to assets/js/6c6ce37c.18a34ffd.js index ff8f356965..780a4d5244 100644 --- a/assets/js/6c6ce37c.16a084ae.js +++ b/assets/js/6c6ce37c.18a34ffd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4692],{4864:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.2/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.2/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.2/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/troubleshooting.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.2/docs",previous:{title:"Internals",permalink:"/docs/4.2/internals"},next:{title:"Migrating",permalink:"/docs/4.2/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4692],{4864:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.2/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.2/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.2/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/troubleshooting.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.2/docs",previous:{title:"Internals",permalink:"/docs/4.2/internals"},next:{title:"Migrating",permalink:"/docs/4.2/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6cfcfcfb.3d2ef2b8.js b/assets/js/6cfcfcfb.f22408b0.js similarity index 98% rename from assets/js/6cfcfcfb.3d2ef2b8.js rename to assets/js/6cfcfcfb.f22408b0.js index a601e2312f..835536e7c8 100644 --- a/assets/js/6cfcfcfb.3d2ef2b8.js +++ b/assets/js/6cfcfcfb.f22408b0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4716],{9949:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=t(7462),p=(t(7294),t(3905));t(1839);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},r=void 0,l={unversionedId:"type_mapping",id:"version-3.0/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-3.0/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/3.0/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/type_mapping.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-3.0/docs",previous:{title:"Mutations",permalink:"/docs/3.0/mutations"},next:{title:"Extending a type",permalink:"/docs/3.0/extend_type"}},o={},s=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2}],u={toc:s},d="wrapper";function c(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/3.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/3.0/custom-output-types"},"custom output types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4716],{9949:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=t(7462),p=(t(7294),t(3905));t(1839);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},r=void 0,l={unversionedId:"type_mapping",id:"version-3.0/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-3.0/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/3.0/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/type_mapping.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-3.0/docs",previous:{title:"Mutations",permalink:"/docs/3.0/mutations"},next:{title:"Extending a type",permalink:"/docs/3.0/extend_type"}},o={},s=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2}],u={toc:s},d="wrapper";function c(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/3.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/3.0/custom-output-types"},"custom output types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6d89025c.fc927e7c.js b/assets/js/6d89025c.091b58f8.js similarity index 99% rename from assets/js/6d89025c.fc927e7c.js rename to assets/js/6d89025c.091b58f8.js index 63c19bb7d8..98731145d4 100644 --- a/assets/js/6d89025c.fc927e7c.js +++ b/assets/js/6d89025c.091b58f8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4519],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},5420:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-6.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/6.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/symfony-bundle-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/6.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/6.0/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4519],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},5420:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-6.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/6.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/symfony-bundle-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"docs",previous:{title:"Class with multiple output types",permalink:"/docs/6.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/6.0/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6efd6ec9.367be157.js b/assets/js/6efd6ec9.cf281cda.js similarity index 98% rename from assets/js/6efd6ec9.367be157.js rename to assets/js/6efd6ec9.cf281cda.js index 99a63784e7..4d88a583d1 100644 --- a/assets/js/6efd6ec9.367be157.js +++ b/assets/js/6efd6ec9.cf281cda.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7870],{6508:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var a=n(7462),p=(n(7294),n(3905));n(1839);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},r=void 0,s={unversionedId:"type_mapping",id:"version-4.0/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.0/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/4.0/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/type_mapping.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-4.0/docs",previous:{title:"Mutations",permalink:"/docs/4.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.0/autowiring"}},l={},o=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},m="wrapper";function c(e){let{components:t,...n}=e;return(0,p.kt)(m,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7870],{6508:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var a=n(7462),p=(n(7294),n(3905));n(1839);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},r=void 0,s={unversionedId:"type_mapping",id:"version-4.0/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.0/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/4.0/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/type_mapping.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-4.0/docs",previous:{title:"Mutations",permalink:"/docs/4.0/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.0/autowiring"}},l={},o=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},m="wrapper";function c(e){let{components:t,...n}=e;return(0,p.kt)(m,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.0/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6fe30f11.05f9db0c.js b/assets/js/6fe30f11.c0b06c25.js similarity index 98% rename from assets/js/6fe30f11.05f9db0c.js rename to assets/js/6fe30f11.c0b06c25.js index 04303fc9c3..2573d600a4 100644 --- a/assets/js/6fe30f11.05f9db0c.js +++ b/assets/js/6fe30f11.c0b06c25.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7991],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},o,{className:(0,s.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},3434:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),o=n(5162);const l={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-3.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-3.0/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/3.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/prefetch_method.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7991],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),o=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&l(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},o,{className:(0,s.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},3434:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),o=n(5162);const l={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-3.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-3.0/prefetch_method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/3.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/prefetch_method.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/71a56230.e92f3cd7.js b/assets/js/71a56230.fb833262.js similarity index 95% rename from assets/js/71a56230.e92f3cd7.js rename to assets/js/71a56230.fb833262.js index 344c8a7742..79112f6a44 100644 --- a/assets/js/71a56230.e92f3cd7.js +++ b/assets/js/71a56230.fb833262.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5235],{473:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.1/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.1/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.1/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/troubleshooting.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-4.1/docs",previous:{title:"Internals",permalink:"/docs/4.1/internals"},next:{title:"Migrating",permalink:"/docs/4.1/migrating"}},l={},u=[],p={toc:u},d="wrapper";function c(e){let{components:t,...o}=e;return(0,r.kt)(d,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5235],{473:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.1/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.1/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.1/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/troubleshooting.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-4.1/docs",previous:{title:"Internals",permalink:"/docs/4.1/internals"},next:{title:"Migrating",permalink:"/docs/4.1/migrating"}},l={},u=[],p={toc:u},d="wrapper";function c(e){let{components:t,...o}=e;return(0,r.kt)(d,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/72d0dc3a.9ea56172.js b/assets/js/72d0dc3a.6b636748.js similarity index 97% rename from assets/js/72d0dc3a.9ea56172.js rename to assets/js/72d0dc3a.6b636748.js index 12e81b2f99..7b58911d7b 100644 --- a/assets/js/72d0dc3a.9ea56172.js +++ b/assets/js/72d0dc3a.6b636748.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3852],{2996:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.3/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.3/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.3/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/troubleshooting.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.3/docs",previous:{title:"Internals",permalink:"/docs/4.3/internals"},next:{title:"Migrating",permalink:"/docs/4.3/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3852],{2996:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-4.3/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-4.3/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/4.3/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/troubleshooting.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.3/docs",previous:{title:"Internals",permalink:"/docs/4.3/internals"},next:{title:"Migrating",permalink:"/docs/4.3/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/741df2ae.fdebd9e2.js b/assets/js/741df2ae.49494839.js similarity index 98% rename from assets/js/741df2ae.fdebd9e2.js rename to assets/js/741df2ae.49494839.js index dea61f8fa1..27d05d16fe 100644 --- a/assets/js/741df2ae.fdebd9e2.js +++ b/assets/js/741df2ae.49494839.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3368],{2220:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>o,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,l={unversionedId:"internals",id:"internals",title:"Internals",description:"Mapping types",source:"@site/docs/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/next/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/internals.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/next/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/next/troubleshooting"}},o={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function c(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/next/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3368],{2220:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>o,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,l={unversionedId:"internals",id:"internals",title:"Internals",description:"Mapping types",source:"@site/docs/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/next/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/internals.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/next/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/next/troubleshooting"}},o={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function c(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/next/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/74383bd8.e8d0f541.js b/assets/js/74383bd8.01881c20.js similarity index 99% rename from assets/js/74383bd8.e8d0f541.js rename to assets/js/74383bd8.01881c20.js index 826d04a946..25cda33efc 100644 --- a/assets/js/74383bd8.e8d0f541.js +++ b/assets/js/74383bd8.01881c20.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7099],{1077:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-6.1/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-6.1/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/internals.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7099],{1077:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-6.1/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-6.1/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/internals.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7515d7ec.83073378.js b/assets/js/7515d7ec.8a2a1484.js similarity index 99% rename from assets/js/7515d7ec.83073378.js rename to assets/js/7515d7ec.8a2a1484.js index f6112e2251..ed9668930e 100644 --- a/assets/js/7515d7ec.83073378.js +++ b/assets/js/7515d7ec.8a2a1484.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2545],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=i??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==s&&(c(t),i(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},1201:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},i=void 0,u={unversionedId:"fine-grained-security",id:"version-3.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-3.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/3.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/fine-grained-security.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"PHP 7")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2545],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=i??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==s&&(c(t),i(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},1201:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},i=void 0,u={unversionedId:"fine-grained-security",id:"version-3.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-3.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/3.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/fine-grained-security.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"PHP 7")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/756c6ac7.24bcb393.js b/assets/js/756c6ac7.1fe3fef5.js similarity index 99% rename from assets/js/756c6ac7.24bcb393.js rename to assets/js/756c6ac7.1fe3fef5.js index 2697714911..6617393845 100644 --- a/assets/js/756c6ac7.24bcb393.js +++ b/assets/js/756c6ac7.1fe3fef5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5811],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},3117:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.3/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.3/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/symfony-bundle-advanced.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-4.3/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.3/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/4.3/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5811],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},3117:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-4.3/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/4.3/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/symfony-bundle-advanced.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-4.3/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.3/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/4.3/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/75cc8326.940f7845.js b/assets/js/75cc8326.f6f786ec.js similarity index 98% rename from assets/js/75cc8326.940f7845.js rename to assets/js/75cc8326.f6f786ec.js index adbff83032..321d1cacaa 100644 --- a/assets/js/75cc8326.940f7845.js +++ b/assets/js/75cc8326.f6f786ec.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4690],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},1504:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.1/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.1/file_uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.1/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/file_uploads.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.1/docs",previous:{title:"Prefetching records",permalink:"/docs/4.1/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.1/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4690],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},1504:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.1/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.1/file_uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.1/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/file_uploads.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.1/docs",previous:{title:"Prefetching records",permalink:"/docs/4.1/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.1/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/766e1cc8.a67bce13.js b/assets/js/766e1cc8.06c37046.js similarity index 99% rename from assets/js/766e1cc8.a67bce13.js rename to assets/js/766e1cc8.06c37046.js index 71e6b7e8e8..93ac806b43 100644 --- a/assets/js/766e1cc8.a67bce13.js +++ b/assets/js/766e1cc8.06c37046.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7294],{1374:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var a=n(7462),o=(n(7294),n(3905));n(1839);const i={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},r=void 0,l={unversionedId:"input-types",id:"version-4.0/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/input-types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-4.0/docs",previous:{title:"External type declaration",permalink:"/docs/4.0/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.0/inheritance-interfaces"}},u={},p=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],s={toc:p},c="wrapper";function d(t){let{components:e,...n}=t;return(0,o.kt)(c,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,o.kt)("p",null,"Your GraphQL query might look like this:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,o.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,o.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,o.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,o.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,o.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,o.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,o.kt)("strong",{parentName:"p"},"Factory"),"."),(0,o.kt)("p",null,"A ",(0,o.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,o.kt)("p",null,"Here is an example of factory:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,o.kt)("p",null,"and now, you can run query like this:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,o.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,o.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,o.kt)("p",null,"A few important things to notice:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,o.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,o.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,o.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,o.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,o.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')),(0,o.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,o.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,o.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,o.kt)("p",null,"You can use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,o.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')),(0,o.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,o.kt)("small",null,"Available in GraphQLite 4.0+"),(0,o.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,o.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,o.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,o.kt)("p",null,"Here is an annotated sample:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')),(0,o.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,o.kt)("small",null,"Available in GraphQLite 4.0+"),(0,o.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,o.kt)("p",null,"Image your ",(0,o.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,o.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')),(0,o.kt)("p",null,"With the ",(0,o.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,o.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7294],{1374:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var a=n(7462),o=(n(7294),n(3905));n(1839);const i={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},r=void 0,l={unversionedId:"input-types",id:"version-4.0/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-4.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/4.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/input-types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-4.0/docs",previous:{title:"External type declaration",permalink:"/docs/4.0/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/4.0/inheritance-interfaces"}},u={},p=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],s={toc:p},c="wrapper";function d(t){let{components:e,...n}=t;return(0,o.kt)(c,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,o.kt)("p",null,"Your GraphQL query might look like this:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,o.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,o.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,o.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,o.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,o.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,o.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,o.kt)("strong",{parentName:"p"},"Factory"),"."),(0,o.kt)("p",null,"A ",(0,o.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,o.kt)("p",null,"Here is an example of factory:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,o.kt)("p",null,"and now, you can run query like this:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,o.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,o.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,o.kt)("p",null,"A few important things to notice:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,o.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,o.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,o.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,o.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,o.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')),(0,o.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,o.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,o.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,o.kt)("p",null,"You can use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,o.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')),(0,o.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,o.kt)("small",null,"Available in GraphQLite 4.0+"),(0,o.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,o.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,o.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,o.kt)("p",null,"Here is an annotated sample:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')),(0,o.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,o.kt)("small",null,"Available in GraphQLite 4.0+"),(0,o.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,o.kt)("p",null,"Image your ",(0,o.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,o.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')),(0,o.kt)("p",null,"With the ",(0,o.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,o.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/767c28af.c728cdd1.js b/assets/js/767c28af.a7e2b841.js similarity index 98% rename from assets/js/767c28af.c728cdd1.js rename to assets/js/767c28af.a7e2b841.js index bf182e42ea..ce821e9fd9 100644 --- a/assets/js/767c28af.c728cdd1.js +++ b/assets/js/767c28af.a7e2b841.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6722],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var r=a(7294),n=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return r.createElement("div",{role:"tabpanel",className:(0,n.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var r=a(7462),n=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function p(e){return function(e){return n.Children.map(e,(e=>{if(!e||(0,n.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:r,default:n}}=e;return{value:t,label:a,attributes:r,default:n}}))}function d(e){const{values:t,children:a}=e;return(0,n.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const r=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,n.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(r.location.search);t.set(l,e),r.replace({...r.location,search:t.toString()})}),[l,r])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:r}=e,l=d(e),[u,o]=(0,n.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:r}),[p,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,l]=(0,c.Nk)(a);return[r,(0,n.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:r}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,n.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,n.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),r=i[a].value;r!==o&&(p(t),s(r))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return n.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return n.createElement("li",(0,r.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:r}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===r));return e?(0,n.cloneElement)(e,{className:"margin-top--md"}):null}return n.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,n.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=b(e);return n.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},n.createElement(v,(0,r.Z)({},e,t)),n.createElement(y,(0,r.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return n.createElement(k,(0,r.Z)({key:String(t)},e))}},7523:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var r=a(7462),n=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},s=void 0,i={unversionedId:"features",id:"version-4.1/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.1/features.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.1/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/features.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.1/docs",next:{title:"Getting Started",permalink:"/docs/4.1/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,n.kt)(m,(0,r.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,n.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,n.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6722],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var r=a(7294),n=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return r.createElement("div",{role:"tabpanel",className:(0,n.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var r=a(7462),n=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function p(e){return function(e){return n.Children.map(e,(e=>{if(!e||(0,n.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:r,default:n}}=e;return{value:t,label:a,attributes:r,default:n}}))}function d(e){const{values:t,children:a}=e;return(0,n.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const r=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,n.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(r.location.search);t.set(l,e),r.replace({...r.location,search:t.toString()})}),[l,r])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:r}=e,l=d(e),[u,o]=(0,n.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:r}),[p,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,l]=(0,c.Nk)(a);return[r,(0,n.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:r}),f=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,n.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,n.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),r=i[a].value;r!==o&&(p(t),s(r))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return n.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return n.createElement("li",(0,r.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:r}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===r));return e?(0,n.cloneElement)(e,{className:"margin-top--md"}):null}return n.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,n.cloneElement)(e,{key:t,hidden:e.props.value!==r}))))}function k(e){const t=b(e);return n.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},n.createElement(v,(0,r.Z)({},e,t)),n.createElement(y,(0,r.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return n.createElement(k,(0,r.Z)({key:String(t)},e))}},7523:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var r=a(7462),n=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},s=void 0,i={unversionedId:"features",id:"version-4.1/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.1/features.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.1/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/features.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.1/docs",next:{title:"Getting Started",permalink:"/docs/4.1/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,n.kt)(m,(0,r.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,n.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,n.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/77cdcd82.eccf4431.js b/assets/js/77cdcd82.58364c16.js similarity index 95% rename from assets/js/77cdcd82.eccf4431.js rename to assets/js/77cdcd82.58364c16.js index 56dd6ac9d0..250c65639d 100644 --- a/assets/js/77cdcd82.eccf4431.js +++ b/assets/js/77cdcd82.58364c16.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6956],{5373:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-6.1/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-6.1/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/troubleshooting.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/internals"},next:{title:"Migrating",permalink:"/docs/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6956],{5373:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-6.1/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-6.1/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/troubleshooting.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/internals"},next:{title:"Migrating",permalink:"/docs/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/78619623.4b050134.js b/assets/js/78619623.81477d8b.js similarity index 99% rename from assets/js/78619623.4b050134.js rename to assets/js/78619623.81477d8b.js index 7dc5a945d9..d490174325 100644 --- a/assets/js/78619623.4b050134.js +++ b/assets/js/78619623.81477d8b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[650],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},3907:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-4.2/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/4.2/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/extend-input-type.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-4.2/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.2/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.2/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[650],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},3907:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-4.2/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/4.2/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/extend-input-type.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-4.2/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.2/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.2/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/78da31a1.6cdc06aa.js b/assets/js/78da31a1.ab83c85b.js similarity index 99% rename from assets/js/78da31a1.6cdc06aa.js rename to assets/js/78da31a1.ab83c85b.js index f6a5a5ebd7..3d99dd966d 100644 --- a/assets/js/78da31a1.6cdc06aa.js +++ b/assets/js/78da31a1.ab83c85b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6564],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!p({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},9988:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},u=void 0,s={unversionedId:"authentication_authorization",id:"version-4.1/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.1/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/4.1/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/authentication_authorization.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-4.1/docs",previous:{title:"User input validation",permalink:"/docs/4.1/validation"},next:{title:"Fine grained security",permalink:"/docs/4.1/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],h={toc:d},p="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6564],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function p(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=h(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!p({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!p({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},p=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},9988:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},u=void 0,s={unversionedId:"authentication_authorization",id:"version-4.1/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.1/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/4.1/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/authentication_authorization.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-4.1/docs",previous:{title:"User input validation",permalink:"/docs/4.1/validation"},next:{title:"Fine grained security",permalink:"/docs/4.1/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],h={toc:d},p="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7afb60b1.c6cd6970.js b/assets/js/7afb60b1.be1b28ca.js similarity index 99% rename from assets/js/7afb60b1.c6cd6970.js rename to assets/js/7afb60b1.be1b28ca.js index 90057b3643..484ff1ba40 100644 --- a/assets/js/7afb60b1.c6cd6970.js +++ b/assets/js/7afb60b1.be1b28ca.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4948],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},8246:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.3/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.3/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.3/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/error-handling.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.3/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.3/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.3/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4948],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},8246:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.3/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.3/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.3/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/error-handling.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.3/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.3/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/4.3/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7b54f5d5.5c60c0d3.js b/assets/js/7b54f5d5.8c106400.js similarity index 99% rename from assets/js/7b54f5d5.5c60c0d3.js rename to assets/js/7b54f5d5.8c106400.js index aa82692690..eb050dbb56 100644 --- a/assets/js/7b54f5d5.5c60c0d3.js +++ b/assets/js/7b54f5d5.8c106400.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2021],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},3746:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-5.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/5.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/multiple-output-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-5.0/docs",previous:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2021],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},3746:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-5.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/5.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/multiple-output-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-5.0/docs",previous:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/5.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7bf967bc.be2f05d3.js b/assets/js/7bf967bc.ab7cb5af.js similarity index 99% rename from assets/js/7bf967bc.be2f05d3.js rename to assets/js/7bf967bc.ab7cb5af.js index 01da712feb..05fd0e9976 100644 --- a/assets/js/7bf967bc.be2f05d3.js +++ b/assets/js/7bf967bc.ab7cb5af.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6390],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),p=a(6550),i=a(1980),o=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,p.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,p]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[i,o]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=i??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&p(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);p(e),o(e),f(e)}),[o,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:p,selectValue:i,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==p&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},o.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:p===t?0:-1,"aria-selected":p===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":p===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(g,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(v,(0,n.Z)({key:String(t)},e))}},7840:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>p,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const p={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},i=void 0,o={unversionedId:"multiple-output-types",id:"multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/docs/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/next/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/multiple-output-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/next/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6390],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),p=a(6550),i=a(1980),o=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,p.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,p]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[i,o]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=i??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&p(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);p(e),o(e),f(e)}),[o,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:p,selectValue:i,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==p&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},o.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:p===t?0:-1,"aria-selected":p===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":p===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(g,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(v,(0,n.Z)({key:String(t)},e))}},7840:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>p,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const p={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},i=void 0,o={unversionedId:"multiple-output-types",id:"multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/docs/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/next/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/multiple-output-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/next/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7c27e34c.44e8bebb.js b/assets/js/7c27e34c.318b2482.js similarity index 95% rename from assets/js/7c27e34c.44e8bebb.js rename to assets/js/7c27e34c.318b2482.js index a22115b201..e2ec83dc9a 100644 --- a/assets/js/7c27e34c.44e8bebb.js +++ b/assets/js/7c27e34c.318b2482.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8091],{9122:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},l=void 0,s={unversionedId:"features",id:"version-3.0/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-3.0/features.mdx",sourceDirName:".",slug:"/",permalink:"/docs/3.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/features.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-3.0/docs",next:{title:"Getting Started",permalink:"/docs/3.0/getting-started"}},o={},u=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(p,(0,r.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony bundle available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8091],{9122:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},l=void 0,s={unversionedId:"features",id:"version-3.0/features",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-3.0/features.mdx",sourceDirName:".",slug:"/",permalink:"/docs/3.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/features.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-3.0/docs",next:{title:"Getting Started",permalink:"/docs/3.0/getting-started"}},o={},u=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(p,(0,r.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",{align:"center"},(0,n.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.kt)("h2",{id:"features"},"Features"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony bundle available!"),(0,n.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,n.kt)("h2",{id:"basic-example"},"Basic example"),(0,n.kt)("p",null,"First, declare a query in your controller:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,n.kt)("p",null,"Then, annotate the ",(0,n.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,n.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7e507331.20797d63.js b/assets/js/7e507331.79ffb9b6.js similarity index 97% rename from assets/js/7e507331.20797d63.js rename to assets/js/7e507331.79ffb9b6.js index ff3571a3ec..6565ac54d6 100644 --- a/assets/js/7e507331.20797d63.js +++ b/assets/js/7e507331.79ffb9b6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1330],{5694:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-5.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-5.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/5.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/semver.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-5.0/docs",previous:{title:"Annotations reference",permalink:"/docs/5.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/5.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1330],{5694:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-5.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-5.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/5.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/semver.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"version-5.0/docs",previous:{title:"Annotations reference",permalink:"/docs/5.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/5.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7e63a40e.8447f445.js b/assets/js/7e63a40e.b7c16e86.js similarity index 98% rename from assets/js/7e63a40e.8447f445.js rename to assets/js/7e63a40e.b7c16e86.js index 3297896259..4d80a35b83 100644 --- a/assets/js/7e63a40e.8447f445.js +++ b/assets/js/7e63a40e.b7c16e86.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9238],{6013:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-4.1/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.1/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/4.1/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/universal_service_providers.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-4.1/docs",previous:{title:"Laravel package",permalink:"/docs/4.1/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.1/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9238],{6013:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-4.1/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.1/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/4.1/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/universal_service_providers.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-4.1/docs",previous:{title:"Laravel package",permalink:"/docs/4.1/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.1/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7ee46e43.8b5fcb11.js b/assets/js/7ee46e43.9d672d82.js similarity index 98% rename from assets/js/7ee46e43.8b5fcb11.js rename to assets/js/7ee46e43.9d672d82.js index 354aef8b12..612adf4643 100644 --- a/assets/js/7ee46e43.8b5fcb11.js +++ b/assets/js/7ee46e43.9d672d82.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6527],{8880:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},r=void 0,l={unversionedId:"input-types",id:"version-3.0/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-3.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/3.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/input-types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-3.0/docs",previous:{title:"External type declaration",permalink:"/docs/3.0/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/3.0/inheritance"}},p={},u=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3}],s={toc:u},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.kt)(c,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,i.kt)("p",null,"Your GraphQL query might look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,i.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,i.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,i.kt)("strong",{parentName:"p"},"Factory"),"."),(0,i.kt)("p",null,"A ",(0,i.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.kt)("p",null,"Here is an example of factory:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,i.kt)("p",null,"and now, you can run query like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,i.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.kt)("p",null,"A few important things to notice:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,i.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,i.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName")\n */\n')),(0,i.kt)("p",null,"Most of the time, the input type name will be completely transparent to you, so there is no real reason\nto customize it."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6527],{8880:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},r=void 0,l={unversionedId:"input-types",id:"version-3.0/input-types",title:"Input types",description:"Let's admit you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-3.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/3.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/input-types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types",original_id:"input-types"},sidebar:"version-3.0/docs",previous:{title:"External type declaration",permalink:"/docs/3.0/external_type_declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/3.0/inheritance"}},p={},u=[{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3}],s={toc:u},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.kt)(c,(0,a.Z)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,i.kt)("p",null,"Your GraphQL query might look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")),(0,i.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,i.kt)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,i.kt)("strong",{parentName:"p"},"Factory"),"."),(0,i.kt)("p",null,"A ",(0,i.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.kt)("p",null,"Here is an example of factory:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")),(0,i.kt)("p",null,"and now, you can run query like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"mutation {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,i.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.kt)("p",null,"A few important things to notice:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,i.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")),(0,i.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName")\n */\n')),(0,i.kt)("p",null,"Most of the time, the input type name will be completely transparent to you, so there is no real reason\nto customize it."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/820db038.2357f1b3.js b/assets/js/820db038.1ddc7111.js similarity index 99% rename from assets/js/820db038.2357f1b3.js rename to assets/js/820db038.1ddc7111.js index 034780f006..a04b7a8593 100644 --- a/assets/js/820db038.2357f1b3.js +++ b/assets/js/820db038.1ddc7111.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9368],{5162:(e,t,n)=>{n.d(t,{Z:()=>s});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function s(e){let{children:t,hidden:n,className:s}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,s),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),i=n(6010),s=n(2466),l=n(6550),p=n(1980),o=n(7392),u=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,p._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[s,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[p,o]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,u.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=p??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:s,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),o(e),y(e)}),[o,y,i]),tabValues:i}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:p,tabValues:o}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,s.o5)(),d=e=>{const t=e.currentTarget,n=u.indexOf(t),a=o[n].value;a!==l&&(c(t),p(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=u.indexOf(e.currentTarget)+1;t=u[n]??u[0];break}case"ArrowLeft":{const n=u.indexOf(e.currentTarget)-1;t=u[n]??u[u.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},o.map((e=>{let{value:t,label:n,attributes:s}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:m,onClick:d},s,{className:(0,i.Z)("tabs__item",g.tabItem,s?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function N(e){const t=y(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(b,(0,a.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return r.createElement(N,(0,a.Z)({key:String(t)},e))}},2988:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>o});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},s=void 0,l={unversionedId:"type-mapping",id:"version-6.1/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-6.1/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/type-mapping.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/mutations"},next:{title:"Autowiring services",permalink:"/docs/autowiring"}},p={},o=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"As explained in the ",(0,r.kt)("a",{parentName:"p",href:"/docs/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,r.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,r.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"string")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"int")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"bool")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"float"))),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,r.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,r.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,r.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,r.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,r.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,r.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,r.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,r.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,r.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,r.kt)("p",null,"GraphQL comes with a native ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,r.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,r.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,r.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,r.kt)("p",null,"You can learn more about forcing output types in the ",(0,r.kt)("a",{parentName:"p",href:"/docs/custom-types"},"custom types section"),"."),(0,r.kt)("h3",{id:"id-class"},"ID class"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,r.kt)("p",null,"Note that you can also use the ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,r.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,r.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,r.kt)("p",null,"When used as an output type, ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,r.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,r.kt)("div",{class:"alert alert--danger"},"PHP ",(0,r.kt)("code",null,"DateTime")," type is not supported."),(0,r.kt)("h2",{id:"union-types"},"Union types"),(0,r.kt)("p",null,"You can create a GraphQL union type ",(0,r.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,r.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")),(0,r.kt)("h2",{id:"enum-types"},"Enum types"),(0,r.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,r.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,r.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,r.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,r.kt)("p",null,"Now, any class extending the ",(0,r.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,r.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,r.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,r.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,r.kt)("p",null,"This will add the ",(0,r.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,r.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,r.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,r.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,r.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,r.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,r.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,r.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,r.kt)("p",null,"If you need more types, you can check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,r.kt)("p",null,"Or if you have some special needs, ",(0,r.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9368],{5162:(e,t,n)=>{n.d(t,{Z:()=>s});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function s(e){let{children:t,hidden:n,className:s}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,s),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),i=n(6010),s=n(2466),l=n(6550),p=n(1980),o=n(7392),u=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,o.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,p._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[s,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[p,o]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,u.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=p??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:s,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),o(e),y(e)}),[o,y,i]),tabValues:i}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:p,tabValues:o}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,s.o5)(),d=e=>{const t=e.currentTarget,n=u.indexOf(t),a=o[n].value;a!==l&&(c(t),p(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=u.indexOf(e.currentTarget)+1;t=u[n]??u[0];break}case"ArrowLeft":{const n=u.indexOf(e.currentTarget)-1;t=u[n]??u[u.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},o.map((e=>{let{value:t,label:n,attributes:s}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>u.push(e),onKeyDown:m,onClick:d},s,{className:(0,i.Z)("tabs__item",g.tabItem,s?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function N(e){const t=y(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(b,(0,a.Z)({},e,t)))}function v(e){const t=(0,f.Z)();return r.createElement(N,(0,a.Z)({key:String(t)},e))}},2988:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>o});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},s=void 0,l={unversionedId:"type-mapping",id:"version-6.1/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-6.1/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/type-mapping.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/mutations"},next:{title:"Autowiring services",permalink:"/docs/autowiring"}},p={},o=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Enum types with myclabs/php-enum",id:"enum-types-with-myclabsphp-enum",level:3},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"As explained in the ",(0,r.kt)("a",{parentName:"p",href:"/docs/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,r.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,r.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"string")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"int")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"bool")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"float"))),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,r.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,r.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,r.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,r.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,r.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,r.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,r.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,r.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')),(0,r.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,r.kt)("p",null,"GraphQL comes with a native ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,r.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,r.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,r.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,r.kt)("p",null,"You can learn more about forcing output types in the ",(0,r.kt)("a",{parentName:"p",href:"/docs/custom-types"},"custom types section"),"."),(0,r.kt)("h3",{id:"id-class"},"ID class"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,r.kt)("p",null,"Note that you can also use the ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")),(0,r.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,r.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,r.kt)("p",null,"When used as an output type, ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,r.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,r.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,r.kt)("div",{class:"alert alert--danger"},"PHP ",(0,r.kt)("code",null,"DateTime")," type is not supported."),(0,r.kt)("h2",{id:"union-types"},"Union types"),(0,r.kt)("p",null,"You can create a GraphQL union type ",(0,r.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,r.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")),(0,r.kt)("h2",{id:"enum-types"},"Enum types"),(0,r.kt)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nenum Status: string\n{\n case ON = 'on';\n case OFF = 'off';\n case PENDING = 'pending';\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return User[]\n */\n#[Query]\npublic function users(Status $status): array\n{\n if ($status === Status::ON) {\n // Your logic\n }\n // ...\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," property on the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,r.kt)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,r.kt)("div",{class:"alert alert--danger"},"This implementation is now deprecated and will be removed in the future. You are advised to use native enums instead."),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,r.kt)("a",{parentName:"em",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),". If you'd like to use this implementation you'll first need to add this library as a dependency to your application.")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,r.kt)("p",null,"Now, any class extending the ",(0,r.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,r.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,r.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,r.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,r.kt)("p",null,"This will add the ",(0,r.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,r.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,r.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,r.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,r.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,r.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,r.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,r.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,r.kt)("p",null,"If you need more types, you can check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,r.kt)("p",null,"Or if you have some special needs, ",(0,r.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/822cd419.9209f1be.js b/assets/js/822cd419.9f2ee9d6.js similarity index 97% rename from assets/js/822cd419.9209f1be.js rename to assets/js/822cd419.9f2ee9d6.js index 9e7128a5dd..e00e36fe13 100644 --- a/assets/js/822cd419.9209f1be.js +++ b/assets/js/822cd419.9f2ee9d6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9271],{9816:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-6.1/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-6.1/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/universal-service-providers.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9271],{9816:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-6.1/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-6.1/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/universal-service-providers.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/82395e72.008a12a5.js b/assets/js/82395e72.221b92eb.js similarity index 99% rename from assets/js/82395e72.008a12a5.js rename to assets/js/82395e72.221b92eb.js index 934a1274d6..a4891145ca 100644 --- a/assets/js/82395e72.008a12a5.js +++ b/assets/js/82395e72.221b92eb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6902],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6011:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-4.3/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.3/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.3/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/validation.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-4.3/docs",previous:{title:"Error handling",permalink:"/docs/4.3/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.3/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6902],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},6011:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-4.3/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.3/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.3/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/validation.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"version-4.3/docs",previous:{title:"Error handling",permalink:"/docs/4.3/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.3/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8299d165.1e2f56c7.js b/assets/js/8299d165.a0a27b49.js similarity index 99% rename from assets/js/8299d165.1e2f56c7.js rename to assets/js/8299d165.a0a27b49.js index 0dc6593a8d..3a951739de 100644 --- a/assets/js/8299d165.1e2f56c7.js +++ b/assets/js/8299d165.a0a27b49.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[924],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},8151:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.3/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.3/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/laravel-package-advanced.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-4.3/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.3/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[924],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},8151:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.3/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.3/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/laravel-package-advanced.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-4.3/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.3/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/843ebfb4.3e27a84c.js b/assets/js/843ebfb4.1adbb5cc.js similarity index 99% rename from assets/js/843ebfb4.3e27a84c.js rename to assets/js/843ebfb4.1adbb5cc.js index 71bb8f70c2..5f4211e1dc 100644 --- a/assets/js/843ebfb4.3e27a84c.js +++ b/assets/js/843ebfb4.1adbb5cc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[772],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},3989:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),i=(a(7294),a(3905)),o=(a(1839),a(4866)),r=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/docs/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/next/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/validation.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/next/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/next/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},h="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[772],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},3989:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),i=(a(7294),a(3905)),o=(a(1839),a(4866)),r=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/docs/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/next/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/validation.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/next/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/next/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},h="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/85339969.8e38e48e.js b/assets/js/85339969.507c1cb5.js similarity index 98% rename from assets/js/85339969.8e38e48e.js rename to assets/js/85339969.507c1cb5.js index 18adfc01db..259c90352e 100644 --- a/assets/js/85339969.8e38e48e.js +++ b/assets/js/85339969.507c1cb5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5307],{3107:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-5.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-5.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/5.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/migrating.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-5.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/5.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/5.0/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/5.0/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5307],{3107:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-5.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-5.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/5.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/migrating.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-5.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/5.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/5.0/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/5.0/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/859fcda7.77d853b7.js b/assets/js/859fcda7.7ee0c73a.js similarity index 97% rename from assets/js/859fcda7.77d853b7.js rename to assets/js/859fcda7.7ee0c73a.js index 939445570b..878be870a7 100644 --- a/assets/js/859fcda7.77d853b7.js +++ b/assets/js/859fcda7.7ee0c73a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9701],{1974:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.1/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.1/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.1/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/getting-started.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-4.1/docs",previous:{title:"GraphQLite",permalink:"/docs/4.1/"},next:{title:"Symfony bundle",permalink:"/docs/4.1/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9701],{1974:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-4.1/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-4.1/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/4.1/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/getting-started.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-4.1/docs",previous:{title:"GraphQLite",permalink:"/docs/4.1/"},next:{title:"Symfony bundle",permalink:"/docs/4.1/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/85c72337.b88b2fa9.js b/assets/js/85c72337.9f918097.js similarity index 99% rename from assets/js/85c72337.b88b2fa9.js rename to assets/js/85c72337.9f918097.js index e974b8db50..f81ec90480 100644 --- a/assets/js/85c72337.b88b2fa9.js +++ b/assets/js/85c72337.9f918097.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6769],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},5513:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-5.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/5.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/symfony-bundle-advanced.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-5.0/docs",previous:{title:"Class with multiple output types",permalink:"/docs/5.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/5.0/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6769],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},5513:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-5.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/5.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/symfony-bundle-advanced.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},sidebar:"version-5.0/docs",previous:{title:"Class with multiple output types",permalink:"/docs/5.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/5.0/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("div",{class:"alert alert--warning"},(0,l.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Symfony bundle specific documentation, please see the ",(0,l.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8913b51a.cb8bac65.js b/assets/js/8913b51a.56bd279a.js similarity index 97% rename from assets/js/8913b51a.cb8bac65.js rename to assets/js/8913b51a.56bd279a.js index b4928a4530..a560701858 100644 --- a/assets/js/8913b51a.cb8bac65.js +++ b/assets/js/8913b51a.56bd279a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8627],{6974:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=a(7462),l=(a(7294),a(3905));a(1839);const i={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={unversionedId:"file-uploads",id:"version-6.1/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-6.1/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/file-uploads.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/prefetch-method"},next:{title:"Pagination",permalink:"/docs/pagination"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.kt)("h2",{id:"installation"},"Installation"),(0,l.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.kt)("p",null,"You must start by installing this package:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,l.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.kt)("p",null,"In order to use this, you must first be sure that the ",(0,l.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.kt)("p",null,"Simply add ",(0,l.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,l.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.kt)("h2",{id:"usage"},"Usage"),(0,l.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,l.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,l.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8627],{6974:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=a(7462),l=(a(7294),a(3905));a(1839);const i={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={unversionedId:"file-uploads",id:"version-6.1/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-6.1/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/file-uploads.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/prefetch-method"},next:{title:"Pagination",permalink:"/docs/pagination"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.kt)("h2",{id:"installation"},"Installation"),(0,l.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.kt)("p",null,"You must start by installing this package:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,l.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.kt)("p",null,"In order to use this, you must first be sure that the ",(0,l.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.kt)("p",null,"Simply add ",(0,l.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,l.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.kt)("h2",{id:"usage"},"Usage"),(0,l.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,l.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,l.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/89cae3a7.629174eb.js b/assets/js/89cae3a7.9aadef3c.js similarity index 99% rename from assets/js/89cae3a7.629174eb.js rename to assets/js/89cae3a7.9aadef3c.js index 84d6906d8b..08f6183055 100644 --- a/assets/js/89cae3a7.629174eb.js +++ b/assets/js/89cae3a7.9aadef3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3229],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},4358:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/docs/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/next/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/external-type-declaration.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/next/extend-type"},next:{title:"Input types",permalink:"/docs/next/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/next/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3229],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},4358:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/docs/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/next/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/external-type-declaration.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/next/extend-type"},next:{title:"Input types",permalink:"/docs/next/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/next/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/89ed63c8.09d04037.js b/assets/js/89ed63c8.87fcb1a0.js similarity index 99% rename from assets/js/89ed63c8.09d04037.js rename to assets/js/89ed63c8.87fcb1a0.js index b19833647b..a0eeec95fd 100644 --- a/assets/js/89ed63c8.09d04037.js +++ b/assets/js/89ed63c8.87fcb1a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3769],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},6939:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-4.3/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.3/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/4.3/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/authentication-authorization.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.3/docs",previous:{title:"User input validation",permalink:"/docs/4.3/validation"},next:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3769],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},6939:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-4.3/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.3/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/4.3/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/authentication-authorization.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.3/docs",previous:{title:"User input validation",permalink:"/docs/4.3/validation"},next:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8b6bafea.26fff7e6.js b/assets/js/8b6bafea.bf2e59f2.js similarity index 98% rename from assets/js/8b6bafea.26fff7e6.js rename to assets/js/8b6bafea.bf2e59f2.js index c13a455a02..d828fe5810 100644 --- a/assets/js/8b6bafea.26fff7e6.js +++ b/assets/js/8b6bafea.bf2e59f2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9780],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2938:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-5.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-5.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/5.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/prefetch-method.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-5.0/docs",previous:{title:"Query plan",permalink:"/docs/5.0/query-plan"},next:{title:"File uploads",permalink:"/docs/5.0/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9780],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2938:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-5.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-5.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/5.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/prefetch-method.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-5.0/docs",previous:{title:"Query plan",permalink:"/docs/5.0/query-plan"},next:{title:"File uploads",permalink:"/docs/5.0/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8bf32d27.0974ffeb.js b/assets/js/8bf32d27.df6bbf23.js similarity index 99% rename from assets/js/8bf32d27.0974ffeb.js rename to assets/js/8bf32d27.df6bbf23.js index 92025a891c..6299ba20ee 100644 --- a/assets/js/8bf32d27.0974ffeb.js +++ b/assets/js/8bf32d27.df6bbf23.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7172],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},3241:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-4.3/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/4.3/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/extend-input-type.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-4.3/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.3/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.3/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7172],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},3241:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-4.3/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/4.3/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/extend-input-type.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"version-4.3/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.3/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.3/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8c95fc16.69a5ba73.js b/assets/js/8c95fc16.051526fe.js similarity index 99% rename from assets/js/8c95fc16.69a5ba73.js rename to assets/js/8c95fc16.051526fe.js index a4daa74574..f048205ef3 100644 --- a/assets/js/8c95fc16.69a5ba73.js +++ b/assets/js/8c95fc16.051526fe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8691],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},2303:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-5.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-5.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/5.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/queries.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-5.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/5.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/5.0/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8691],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},2303:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-5.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-5.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/5.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/queries.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"version-5.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/5.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/5.0/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/8d81badd.bf29df04.js b/assets/js/8d81badd.1daf10fc.js similarity index 98% rename from assets/js/8d81badd.bf29df04.js rename to assets/js/8d81badd.1daf10fc.js index bf5bce4c9f..bcde9d8bf6 100644 --- a/assets/js/8d81badd.bf29df04.js +++ b/assets/js/8d81badd.1daf10fc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1396],{3357:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-6.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/6.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/argument-resolving.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1396],{3357:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-6.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/6.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/argument-resolving.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8f7abfe1.577c9821.js b/assets/js/8f7abfe1.f46038e4.js similarity index 98% rename from assets/js/8f7abfe1.577c9821.js rename to assets/js/8f7abfe1.f46038e4.js index f00eb39fbe..54a1bfc8cc 100644 --- a/assets/js/8f7abfe1.577c9821.js +++ b/assets/js/8f7abfe1.f46038e4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6978],{4069:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},l=void 0,o={unversionedId:"queries",id:"version-3.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-3.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/3.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/queries.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-3.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/3.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/3.0/mutations"}},s={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],u={toc:p},h="wrapper";function d(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6978],{4069:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},l=void 0,o={unversionedId:"queries",id:"version-3.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-3.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/3.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/queries.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-3.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/3.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/3.0/mutations"}},s={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],u={toc:p},h="wrapper";function d(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/8f7fa040.e17cd78a.js b/assets/js/8f7fa040.c37651ec.js similarity index 98% rename from assets/js/8f7fa040.e17cd78a.js rename to assets/js/8f7fa040.c37651ec.js index c172760d33..f2bbf282af 100644 --- a/assets/js/8f7fa040.e17cd78a.js +++ b/assets/js/8f7fa040.c37651ec.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1820],{5646:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},o=void 0,l={unversionedId:"extend_type",id:"version-4.0/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.0/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/4.0/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/extend_type.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-4.0/docs",previous:{title:"Autowiring services",permalink:"/docs/4.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.0/external_type_declaration"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,i.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," method in the product because the name needs to be translated in the correct language. You have a ",(0,i.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,i.kt)("p",null,"Using ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,i.kt)("p",null,"Let's break this sample:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"With the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,i.kt)("p",null,'Using the "',(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1820],{5646:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},o=void 0,l={unversionedId:"extend_type",id:"version-4.0/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.0/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/4.0/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/extend_type.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-4.0/docs",previous:{title:"Autowiring services",permalink:"/docs/4.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.0/external_type_declaration"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,i.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," method in the product because the name needs to be translated in the correct language. You have a ",(0,i.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,i.kt)("p",null,"Using ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,i.kt)("p",null,"Let's break this sample:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"With the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,i.kt)("p",null,'Using the "',(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8f951ce3.74067c36.js b/assets/js/8f951ce3.8bd0aae6.js similarity index 98% rename from assets/js/8f951ce3.74067c36.js rename to assets/js/8f951ce3.8bd0aae6.js index aff53b6d07..a003fcabf1 100644 --- a/assets/js/8f951ce3.74067c36.js +++ b/assets/js/8f951ce3.8bd0aae6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8734],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8905:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.2/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.2/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.2/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/prefetch-method.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-4.2/docs",previous:{title:"Query plan",permalink:"/docs/4.2/query-plan"},next:{title:"File uploads",permalink:"/docs/4.2/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8734],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8905:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.2/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.2/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.2/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/prefetch-method.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-4.2/docs",previous:{title:"Query plan",permalink:"/docs/4.2/query-plan"},next:{title:"File uploads",permalink:"/docs/4.2/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8f967659.c22094f1.js b/assets/js/8f967659.e5513f88.js similarity index 96% rename from assets/js/8f967659.c22094f1.js rename to assets/js/8f967659.e5513f88.js index 3ff02584b6..f949d74a3e 100644 --- a/assets/js/8f967659.c22094f1.js +++ b/assets/js/8f967659.e5513f88.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[766],{2590:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-3.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-3.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/3.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/semver.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"}},l={},p=[],m={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[766],{2590:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-3.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-3.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/3.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/semver.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"}},l={},p=[],m={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9000b231.daf1ecbd.js b/assets/js/9000b231.818ff52b.js similarity index 98% rename from assets/js/9000b231.daf1ecbd.js rename to assets/js/9000b231.818ff52b.js index ba7a808f0e..e4e395e15d 100644 --- a/assets/js/9000b231.daf1ecbd.js +++ b/assets/js/9000b231.818ff52b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9872],{8962:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"},l=void 0,o={unversionedId:"migrating",id:"version-3.0/migrating",title:"Release notes",description:"First stable release of GraphQLite",source:"@site/versioned_docs/version-3.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/3.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/migrating.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},d=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"first-stable-release-of-graphqlite"},"First stable release of GraphQLite"),(0,r.kt)("p",null,"GraphQLite is PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony and Laravel bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,r.kt)("p",null,"After several months of work, we are very happy to announce the availability of GraphQLite v3.0."),(0,r.kt)("p",null,'If you are wondering where are v1 and v2... yeah... GraphQLite is a fork of "thecodingmachine/graphql-controllers" that already had a v1 and a v2. But so much has changed that it deserved a new name!'),(0,r.kt)("p",null,(0,r.kt)("a",{parentName:"p",href:"https://graphqlite.thecodingmachine.io"},"Check out the documentation")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,r.kt)("p",null,"That's it, you're good to go \ud83c\udf89! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9872],{8962:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"},l=void 0,o={unversionedId:"migrating",id:"version-3.0/migrating",title:"Release notes",description:"First stable release of GraphQLite",source:"@site/versioned_docs/version-3.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/3.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/migrating.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},d=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},u="wrapper";function c(e){let{components:t,...a}=e;return(0,r.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"first-stable-release-of-graphqlite"},"First stable release of GraphQLite"),(0,r.kt)("p",null,"GraphQLite is PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony and Laravel bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,r.kt)("p",null,"After several months of work, we are very happy to announce the availability of GraphQLite v3.0."),(0,r.kt)("p",null,'If you are wondering where are v1 and v2... yeah... GraphQLite is a fork of "thecodingmachine/graphql-controllers" that already had a v1 and a v2. But so much has changed that it deserved a new name!'),(0,r.kt)("p",null,(0,r.kt)("a",{parentName:"p",href:"https://graphqlite.thecodingmachine.io"},"Check out the documentation")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")),(0,r.kt)("p",null,"That's it, you're good to go \ud83c\udf89! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9073923c.3b388fc3.js b/assets/js/9073923c.4d345ff0.js similarity index 98% rename from assets/js/9073923c.3b388fc3.js rename to assets/js/9073923c.4d345ff0.js index e6066f5215..e161e3df44 100644 --- a/assets/js/9073923c.3b388fc3.js +++ b/assets/js/9073923c.4d345ff0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5795],{7867:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>y,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const s={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},o=void 0,i={unversionedId:"custom-output-types",id:"version-4.1/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.1/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/4.1/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/custom_output_types.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function y(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5795],{7867:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>y,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(7462),p=(a(7294),a(3905));a(1839);const s={id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"},o=void 0,i={unversionedId:"custom-output-types",id:"version-4.1/custom-output-types",title:"Custom output types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.1/custom_output_types.md",sourceDirName:".",slug:"/custom-output-types",permalink:"/docs/4.1/custom-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/custom_output_types.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-output-types",title:"Custom output types",sidebar_label:"Custom output types",original_id:"custom-output-types"}},u={},l=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3}],r={toc:l},d="wrapper";function y(e){let{components:t,...a}=e;return(0,p.kt)(d,(0,n.Z)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/90e0b7fd.b7ab9344.js b/assets/js/90e0b7fd.d0b658f7.js similarity index 99% rename from assets/js/90e0b7fd.b7ab9344.js rename to assets/js/90e0b7fd.d0b658f7.js index 22e68d8bf8..88c184a0b8 100644 --- a/assets/js/90e0b7fd.b7ab9344.js +++ b/assets/js/90e0b7fd.d0b658f7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5314],{7457:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-6.1/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/laravel-package.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5314],{7457:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-6.1/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/laravel-package.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9206a32f.b2bca24e.js b/assets/js/9206a32f.5cb7cf65.js similarity index 98% rename from assets/js/9206a32f.b2bca24e.js rename to assets/js/9206a32f.5cb7cf65.js index 5251ec7c81..797530ad45 100644 --- a/assets/js/9206a32f.b2bca24e.js +++ b/assets/js/9206a32f.5cb7cf65.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3355],{5573:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-6.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-6.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/6.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/migrating.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/6.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/6.0/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/6.0/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3355],{5573:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-6.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-6.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/6.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/migrating.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/6.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/6.0/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/6.0/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9279cea7.37d66749.js b/assets/js/9279cea7.909fcd8a.js similarity index 99% rename from assets/js/9279cea7.37d66749.js rename to assets/js/9279cea7.909fcd8a.js index 5e9cde12d7..623d09e950 100644 --- a/assets/js/9279cea7.37d66749.js +++ b/assets/js/9279cea7.909fcd8a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[169],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},6235:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.1/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.1/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.1/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/custom_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},sidebar:"version-4.1/docs",previous:{title:"Pagination",permalink:"/docs/4.1/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.1/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[169],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},6235:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.1/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.1/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.1/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/custom_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},sidebar:"version-4.1/docs",previous:{title:"Pagination",permalink:"/docs/4.1/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.1/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/947f2c39.2d271b64.js b/assets/js/947f2c39.6adad4d3.js similarity index 98% rename from assets/js/947f2c39.2d271b64.js rename to assets/js/947f2c39.6adad4d3.js index 99cf5db4ad..5e94814e22 100644 --- a/assets/js/947f2c39.2d271b64.js +++ b/assets/js/947f2c39.6adad4d3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6489],{5146:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var n=a(7462),p=(a(7294),a(3905));a(1839);const o={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},r=void 0,i={unversionedId:"custom-types",id:"version-4.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.0/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/custom_types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},sidebar:"version-4.0/docs",previous:{title:"Pagination",permalink:"/docs/4.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.0/field-middlewares"}},l={},s=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],u={toc:s},y="wrapper";function c(e){let{components:t,...a}=e;return(0,p.kt)(y,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."),(0,p.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,p.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},"create a ",(0,p.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,p.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,p.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.kt)("p",null,"RootTypeMapper are organized ",(0,p.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType\n */\n public function mapNameToType(string $typeName): NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return $this->next->mapNameToType($typeName);\n }\n}\n')),(0,p.kt)("p",null,"Now, in order to create an instance of your ",(0,p.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,p.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.kt)("p",null,"You can register your own root mapper factories using the ",(0,p.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6489],{5146:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var n=a(7462),p=(a(7294),a(3905));a(1839);const o={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},r=void 0,i={unversionedId:"custom-types",id:"version-4.0/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.0/custom_types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/custom_types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},sidebar:"version-4.0/docs",previous:{title:"Pagination",permalink:"/docs/4.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.0/field-middlewares"}},l={},s=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],u={toc:s},y="wrapper";function c(e){let{components:t,...a}=e;return(0,p.kt)(y,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field(name="id")\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n')),(0,p.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.kt)("p",null,"GraphQL comes with an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')),(0,p.kt)("h2",{id:"usage"},"Usage"),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.kt)("p",null,"You can use the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Query")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@Field")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,p.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.kt)("p",null,"In order to create a custom output type, you need to:"),(0,p.kt)("ol",null,(0,p.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.kt)("p",null,"You'll find more details on the ",(0,p.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.kt)("hr",null),(0,p.kt)("p",null,"In order to find existing types, the schema is using ",(0,p.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,p.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,p.kt)("p",null,"Any class extending ",(0,p.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,p.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,p.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,p.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.kt)("p",null,"The easiest way is to use a ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.kt)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."),(0,p.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,p.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},"create a ",(0,p.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,p.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,p.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): OutputType;\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,p.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.kt)("p",null,"RootTypeMapper are organized ",(0,p.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.kt)("p",null,"For instance:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType\n */\n public function mapNameToType(string $typeName): NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return $this->next->mapNameToType($typeName);\n }\n}\n')),(0,p.kt)("p",null,"Now, in order to create an instance of your ",(0,p.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,p.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.kt)("p",null,"You can register your own root mapper factories using the ",(0,p.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/95576100.7f157755.js b/assets/js/95576100.0a64d2ef.js similarity index 99% rename from assets/js/95576100.7f157755.js rename to assets/js/95576100.0a64d2ef.js index 14cf9e56f7..f508b94f62 100644 --- a/assets/js/95576100.7f157755.js +++ b/assets/js/95576100.0a64d2ef.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9422],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6363:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-4.3/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.3/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.3/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/autowiring.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-4.3/docs",previous:{title:"Type mapping",permalink:"/docs/4.3/type-mapping"},next:{title:"Extending a type",permalink:"/docs/4.3/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9422],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6363:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-4.3/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.3/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.3/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/autowiring.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"version-4.3/docs",previous:{title:"Type mapping",permalink:"/docs/4.3/type-mapping"},next:{title:"Extending a type",permalink:"/docs/4.3/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9664ee55.6f31d682.js b/assets/js/9664ee55.057665d8.js similarity index 99% rename from assets/js/9664ee55.6f31d682.js rename to assets/js/9664ee55.057665d8.js index 8dfbaad523..3033707f70 100644 --- a/assets/js/9664ee55.6f31d682.js +++ b/assets/js/9664ee55.057665d8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3534],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},7272:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-4.2/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-4.2/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.2/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/other-frameworks.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-4.2/docs",previous:{title:"Universal service providers",permalink:"/docs/4.2/universal-service-providers"},next:{title:"Queries",permalink:"/docs/4.2/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3534],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},7272:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-4.2/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-4.2/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.2/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/other-frameworks.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-4.2/docs",previous:{title:"Universal service providers",permalink:"/docs/4.2/universal-service-providers"},next:{title:"Queries",permalink:"/docs/4.2/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/96877411.6d0c752f.js b/assets/js/96877411.2895f908.js similarity index 99% rename from assets/js/96877411.6d0c752f.js rename to assets/js/96877411.2895f908.js index ad62a797e1..95b9abf975 100644 --- a/assets/js/96877411.6d0c752f.js +++ b/assets/js/96877411.2895f908.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1606],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1053:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/docs/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/next/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/extend-type.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/next/autowiring"},next:{title:"External type declaration",permalink:"/docs/next/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1606],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1053:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/docs/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/next/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/extend-type.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/next/autowiring"},next:{title:"External type declaration",permalink:"/docs/next/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9749ab4a.401fd048.js b/assets/js/9749ab4a.869cf3a9.js similarity index 99% rename from assets/js/9749ab4a.401fd048.js rename to assets/js/9749ab4a.869cf3a9.js index a68c50e2a4..d91d9ee6f1 100644 --- a/assets/js/9749ab4a.401fd048.js +++ b/assets/js/9749ab4a.869cf3a9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4235],{5371:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-5.0/changelog",title:"Changelog",description:"5.0.0",source:"@site/versioned_docs/version-5.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/5.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/CHANGELOG.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-5.0/docs",previous:{title:"Semantic versioning",permalink:"/docs/5.0/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4235],{5371:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-5.0/changelog",title:"Changelog",description:"5.0.0",source:"@site/versioned_docs/version-5.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/5.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/CHANGELOG.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"version-5.0/docs",previous:{title:"Semantic versioning",permalink:"/docs/5.0/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/input-types#input-annotation"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/5.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/976f6afc.b31f2cb2.js b/assets/js/976f6afc.904f12c9.js similarity index 98% rename from assets/js/976f6afc.b31f2cb2.js rename to assets/js/976f6afc.904f12c9.js index 9fc43ab945..98c2e8e522 100644 --- a/assets/js/976f6afc.b31f2cb2.js +++ b/assets/js/976f6afc.904f12c9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4866],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},4945:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.1/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.1/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.1/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/mutations.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-4.1/docs",previous:{title:"Queries",permalink:"/docs/4.1/queries"},next:{title:"Type mapping",permalink:"/docs/4.1/type_mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4866],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},4945:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.1/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.1/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.1/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/mutations.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations",original_id:"mutations"},sidebar:"version-4.1/docs",previous:{title:"Queries",permalink:"/docs/4.1/queries"},next:{title:"Type mapping",permalink:"/docs/4.1/type_mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9953ecde.0c20885c.js b/assets/js/9953ecde.dc002d88.js similarity index 97% rename from assets/js/9953ecde.0c20885c.js rename to assets/js/9953ecde.dc002d88.js index 22a00c21e7..b15c537a2a 100644 --- a/assets/js/9953ecde.0c20885c.js +++ b/assets/js/9953ecde.dc002d88.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1407],{4821:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/docs/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/next/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/semver.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/next/annotations-reference"},next:{title:"Changelog",permalink:"/docs/next/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1407],{4821:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/docs/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/next/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/semver.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/next/annotations-reference"},next:{title:"Changelog",permalink:"/docs/next/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9bd507da.48d97c2b.js b/assets/js/9bd507da.6274f204.js similarity index 98% rename from assets/js/9bd507da.48d97c2b.js rename to assets/js/9bd507da.6274f204.js index be25203806..d3ce245d8c 100644 --- a/assets/js/9bd507da.48d97c2b.js +++ b/assets/js/9bd507da.6274f204.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6868],{2070:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.2/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-4.2/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.2/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/implementing-security.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-4.2/docs",previous:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.2/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6868],{2070:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.2/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-4.2/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.2/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/implementing-security.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-4.2/docs",previous:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.2/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9d336ee4.f08b914d.js b/assets/js/9d336ee4.43e96d65.js similarity index 99% rename from assets/js/9d336ee4.f08b914d.js rename to assets/js/9d336ee4.43e96d65.js index 53b8e369d1..9afa24c2d1 100644 --- a/assets/js/9d336ee4.f08b914d.js +++ b/assets/js/9d336ee4.43e96d65.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1293],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},8044:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-6.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-6.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/6.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/queries.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/6.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/6.0/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1293],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},8044:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-6.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-6.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/6.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/queries.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/6.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/6.0/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/9d9f8394.98f72146.js b/assets/js/9d9f8394.3443ecf0.js similarity index 97% rename from assets/js/9d9f8394.98f72146.js rename to assets/js/9d9f8394.3443ecf0.js index 75851851cd..ba90145d92 100644 --- a/assets/js/9d9f8394.98f72146.js +++ b/assets/js/9d9f8394.3443ecf0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9360],{9222:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>a,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},a=void 0,s={unversionedId:"troubleshooting",id:"troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/docs/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/next/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/troubleshooting.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/next/internals"},next:{title:"Migrating",permalink:"/docs/next/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9360],{9222:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>a,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},a=void 0,s={unversionedId:"troubleshooting",id:"troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/docs/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/next/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/troubleshooting.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/next/internals"},next:{title:"Migrating",permalink:"/docs/next/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9f0ecd2e.4ce3b9ac.js b/assets/js/9f0ecd2e.d55ede3b.js similarity index 98% rename from assets/js/9f0ecd2e.4ce3b9ac.js rename to assets/js/9f0ecd2e.d55ede3b.js index 07b7afb272..e7a7826bbb 100644 --- a/assets/js/9f0ecd2e.4ce3b9ac.js +++ b/assets/js/9f0ecd2e.d55ede3b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9001],{8313:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-6.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/field-middlewares.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9001],{8313:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-6.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/field-middlewares.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a0bf4a5f.c74b5b59.js b/assets/js/a0bf4a5f.ed20eed6.js similarity index 98% rename from assets/js/a0bf4a5f.c74b5b59.js rename to assets/js/a0bf4a5f.ed20eed6.js index 5adc5b9132..8f62c7287f 100644 --- a/assets/js/a0bf4a5f.c74b5b59.js +++ b/assets/js/a0bf4a5f.ed20eed6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7539],{3471:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.3/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.3/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/field-middlewares.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-4.3/docs",previous:{title:"Custom types",permalink:"/docs/4.3/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.3/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7539],{3471:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.3/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.3/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/field-middlewares.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-4.3/docs",previous:{title:"Custom types",permalink:"/docs/4.3/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.3/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a13f3cdc.37d31e6a.js b/assets/js/a13f3cdc.6f484099.js similarity index 98% rename from assets/js/a13f3cdc.37d31e6a.js rename to assets/js/a13f3cdc.6f484099.js index 20480d0695..1ba2ed25d7 100644 --- a/assets/js/a13f3cdc.37d31e6a.js +++ b/assets/js/a13f3cdc.6f484099.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4754],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},5567:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.3/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.3/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.3/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/prefetch-method.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-4.3/docs",previous:{title:"Query plan",permalink:"/docs/4.3/query-plan"},next:{title:"File uploads",permalink:"/docs/4.3/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4754],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},5567:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-4.3/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.3/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.3/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/prefetch-method.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"version-4.3/docs",previous:{title:"Query plan",permalink:"/docs/4.3/query-plan"},next:{title:"File uploads",permalink:"/docs/4.3/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a16ee953.e022575c.js b/assets/js/a16ee953.cc3b8ffc.js similarity index 98% rename from assets/js/a16ee953.e022575c.js rename to assets/js/a16ee953.cc3b8ffc.js index 44ad44a8de..f701842b29 100644 --- a/assets/js/a16ee953.e022575c.js +++ b/assets/js/a16ee953.cc3b8ffc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8929],{8770:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-6.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-6.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/6.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/internals.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/6.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/6.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/6.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8929],{8770:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-6.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-6.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/6.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/internals.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/6.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/6.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eEnumTypeMapper\n EnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/6.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a1e3d512.3c41b541.js b/assets/js/a1e3d512.c9753d80.js similarity index 99% rename from assets/js/a1e3d512.3c41b541.js rename to assets/js/a1e3d512.c9753d80.js index 5e7e797676..638fc90021 100644 --- a/assets/js/a1e3d512.3c41b541.js +++ b/assets/js/a1e3d512.c9753d80.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[634],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),i=a(6010),l=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,i]),tabValues:i}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,i.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},2535:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),l=a(5162);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.1/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/fine-grained-security.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},sidebar:"version-4.1/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.1/authentication_authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.1/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"PHP 7")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[634],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),i=a(6010),l=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,i]),tabValues:i}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,i.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},2535:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),l=a(5162);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.1/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/fine-grained-security.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},sidebar:"version-4.1/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.1/authentication_authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.1/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"PHP 7")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a23a5b68.de412bf7.js b/assets/js/a23a5b68.c894cd66.js similarity index 99% rename from assets/js/a23a5b68.de412bf7.js rename to assets/js/a23a5b68.c894cd66.js index de54288aa7..3363a0746d 100644 --- a/assets/js/a23a5b68.de412bf7.js +++ b/assets/js/a23a5b68.c894cd66.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4499],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6096:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-6.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/6.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/6.0/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4499],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},6096:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-6.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/6.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/6.0/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a264d631.f792823f.js b/assets/js/a264d631.9a1b1bd1.js similarity index 99% rename from assets/js/a264d631.f792823f.js rename to assets/js/a264d631.9a1b1bd1.js index 9d6bda306d..cbc1fc695a 100644 --- a/assets/js/a264d631.f792823f.js +++ b/assets/js/a264d631.9a1b1bd1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1569],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},893:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-5.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-5.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/5.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/error-handling.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-5.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/5.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/5.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1569],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>w});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function w(e){const n=(0,f.Z)();return a.createElement(v,(0,r.Z)({key:String(n)},e))}},893:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-5.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-5.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/5.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/error-handling.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-5.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/5.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/5.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/5.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a27f6be0.1422b8c7.js b/assets/js/a27f6be0.5a1578c0.js similarity index 96% rename from assets/js/a27f6be0.1422b8c7.js rename to assets/js/a27f6be0.5a1578c0.js index e3c57f1a71..9068eb444e 100644 --- a/assets/js/a27f6be0.1422b8c7.js +++ b/assets/js/a27f6be0.5a1578c0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6357],{6147:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.1/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-4.1/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.1/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/implementing-security.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},sidebar:"version-4.1/docs",previous:{title:"Fine grained security",permalink:"/docs/4.1/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.1/query-plan"}},u={},c=[],l={toc:c},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6357],{6147:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>c});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.1/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-4.1/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.1/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/implementing-security.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework",original_id:"implementing-security"},sidebar:"version-4.1/docs",previous:{title:"Fine grained security",permalink:"/docs/4.1/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.1/query-plan"}},u={},c=[],l={toc:c},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a28aff23.a01aef11.js b/assets/js/a28aff23.a8081c43.js similarity index 99% rename from assets/js/a28aff23.a01aef11.js rename to assets/js/a28aff23.a8081c43.js index b5b9366b1a..d37e5bbc42 100644 --- a/assets/js/a28aff23.a01aef11.js +++ b/assets/js/a28aff23.a8081c43.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7276],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},6875:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-6.0/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-6.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/6.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/authentication-authorization.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.0/validation"},next:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7276],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},6875:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-6.0/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-6.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/6.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/authentication-authorization.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.0/validation"},next:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a2d3d8d2.13c6fb19.js b/assets/js/a2d3d8d2.2daaa519.js similarity index 99% rename from assets/js/a2d3d8d2.13c6fb19.js rename to assets/js/a2d3d8d2.2daaa519.js index aa0f0f8ce3..72bd4dfb5d 100644 --- a/assets/js/a2d3d8d2.13c6fb19.js +++ b/assets/js/a2d3d8d2.2daaa519.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4877],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},5085:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-6.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/6.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/extend-input-type.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/6.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/6.0/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4877],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},5085:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend-input-type",id:"version-6.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/6.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/extend-input-type.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},sidebar:"docs",previous:{title:"Custom argument resolving",permalink:"/docs/6.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/6.0/multiple-output-types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/extend-type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a30fd8ca.dfc6df95.js b/assets/js/a30fd8ca.d5c8e65e.js similarity index 98% rename from assets/js/a30fd8ca.dfc6df95.js rename to assets/js/a30fd8ca.d5c8e65e.js index adf91f6001..a6a2050a28 100644 --- a/assets/js/a30fd8ca.dfc6df95.js +++ b/assets/js/a30fd8ca.d5c8e65e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3545],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},6633:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},u=void 0,s={unversionedId:"extend_input_type",id:"version-4.1/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/4.1/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/extend_input_type.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},sidebar:"version-4.1/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.1/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/extend_type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3545],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=h({queryString:a,groupId:n}),[c,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},6633:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},u=void 0,s={unversionedId:"extend_input_type",id:"version-4.1/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/4.1/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/extend_input_type.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type",original_id:"extend_input_type"},sidebar:"version-4.1/docs",previous:{title:"Custom argument resolving",permalink:"/docs/4.1/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"}},p={},c=[],d={toc:c},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/extend_type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a320b509.adb1eb4e.js b/assets/js/a320b509.0b11ed31.js similarity index 98% rename from assets/js/a320b509.adb1eb4e.js rename to assets/js/a320b509.0b11ed31.js index 21d00b52a6..b37db5ca2c 100644 --- a/assets/js/a320b509.adb1eb4e.js +++ b/assets/js/a320b509.0b11ed31.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8612],{364:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-3.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/3.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/field_middlewares.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8612],{364:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-3.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/3.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/field_middlewares.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface\nis a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation\nis to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a3a193a6.7e8710f4.js b/assets/js/a3a193a6.9e84f3bc.js similarity index 97% rename from assets/js/a3a193a6.7e8710f4.js rename to assets/js/a3a193a6.9e84f3bc.js index 92741c1f2c..bc37663e04 100644 --- a/assets/js/a3a193a6.7e8710f4.js +++ b/assets/js/a3a193a6.9e84f3bc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2499],{7848:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},o=void 0,s={unversionedId:"semver",id:"version-4.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-4.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/semver.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.0/docs",previous:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.0/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,n.kt)(d,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2499],{7848:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},o=void 0,s={unversionedId:"semver",id:"version-4.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all",source:"@site/versioned_docs/version-4.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/4.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/semver.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.0/docs",previous:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.0/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,n.kt)(d,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all\nminor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short,\nSemantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility.\nMinor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of\nthat release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library.\nThey are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a55b0daf.fb56f0b7.js b/assets/js/a55b0daf.6a64689e.js similarity index 99% rename from assets/js/a55b0daf.fb56f0b7.js rename to assets/js/a55b0daf.6a64689e.js index 2365d35698..fd0de95f45 100644 --- a/assets/js/a55b0daf.fb56f0b7.js +++ b/assets/js/a55b0daf.6a64689e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4317],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8587:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/docs/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/next/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/other-frameworks.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/next/universal-service-providers"},next:{title:"Queries",permalink:"/docs/next/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n\n// Configure the server to use Apollo automatic persisted queries with given cache and an optional time-to-live.\n// See https://www.apollographql.com/docs/apollo-server/performance/apq/\n$builder->useAutomaticPersistedQueries($cache, new DateInterval('PT1H'));\n")),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4317],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8587:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/docs/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/next/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/other-frameworks.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"docs",previous:{title:"Universal service providers",permalink:"/docs/next/universal-service-providers"},next:{title:"Queries",permalink:"/docs/next/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Set a default InputType validator service to handle validation on all `Input` annotated types\n$factory->setInputTypeValidator($validator);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$builder->setUrl(\"/graphql\"); // Modify the URL endpoint (defaults to /graphql)\n\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object.\n// Define your own formatter and error handlers for Webonyx.\n$config->setErrorFormatter([ExceptionHandler::class, 'errorFormatter']);\n$config->setErrorsHandler([ExceptionHandler::class, 'errorHandler']);\n\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n\n// Configure the server to use Apollo automatic persisted queries with given cache and an optional time-to-live.\n// See https://www.apollographql.com/docs/apollo-server/performance/apq/\n$builder->useAutomaticPersistedQueries($cache, new DateInterval('PT1H'));\n")),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a95c9e82.6c5dc87f.js b/assets/js/a95c9e82.953d011b.js similarity index 99% rename from assets/js/a95c9e82.6c5dc87f.js rename to assets/js/a95c9e82.953d011b.js index 76c439b64a..fe2f6cb6ea 100644 --- a/assets/js/a95c9e82.6c5dc87f.js +++ b/assets/js/a95c9e82.953d011b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4168],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2913:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.3/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.3/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.3/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/mutations.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-4.3/docs",previous:{title:"Queries",permalink:"/docs/4.3/queries"},next:{title:"Type mapping",permalink:"/docs/4.3/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4168],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2913:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-4.3/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-4.3/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/4.3/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/mutations.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-4.3/docs",previous:{title:"Queries",permalink:"/docs/4.3/queries"},next:{title:"Type mapping",permalink:"/docs/4.3/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a99e9943.1db41608.js b/assets/js/a99e9943.4187a1d0.js similarity index 98% rename from assets/js/a99e9943.1db41608.js rename to assets/js/a99e9943.4187a1d0.js index 3e1a01888d..b8787dc91e 100644 --- a/assets/js/a99e9943.1db41608.js +++ b/assets/js/a99e9943.4187a1d0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3725],{281:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.3/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-4.3/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.3/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/implementing-security.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-4.3/docs",previous:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.3/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3725],{281:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-4.3/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-4.3/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/4.3/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/implementing-security.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"version-4.3/docs",previous:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/4.3/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a9bc4f03.1c9d5a72.js b/assets/js/a9bc4f03.40176044.js similarity index 99% rename from assets/js/a9bc4f03.1c9d5a72.js rename to assets/js/a9bc4f03.40176044.js index 8774e31f45..2403c5cd9e 100644 --- a/assets/js/a9bc4f03.1c9d5a72.js +++ b/assets/js/a9bc4f03.40176044.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3699],{4078:(t,a,e)=>{e.r(a),e.d(a,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=e(7462),i=(e(7294),e(3905));e(1839);const o={id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},r=void 0,l={unversionedId:"validation",id:"version-4.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/validation.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},sidebar:"version-4.0/docs",previous:{title:"Error handling",permalink:"/docs/4.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.0/authentication_authorization"}},s={},d=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],u={toc:d},p="wrapper";function c(t){let{components:a,...e}=t;return(0,i.kt)(p,(0,n.Z)({},u,e,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,i.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"UserController.php")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"User.php")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3699],{4078:(t,a,e)=>{e.r(a),e.d(a,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=e(7462),i=(e(7294),e(3905));e(1839);const o={id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},r=void 0,l={unversionedId:"validation",id:"version-4.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/validation.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},sidebar:"version-4.0/docs",previous:{title:"Error handling",permalink:"/docs/4.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.0/authentication_authorization"}},s={},d=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],u={toc:d},p="wrapper";function c(t){let{components:a,...e}=t;return(0,i.kt)(p,(0,n.Z)({},u,e,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,i.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"UserController.php")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"User.php")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/aa52484c.8eb1f6e7.js b/assets/js/aa52484c.6a6d21da.js similarity index 98% rename from assets/js/aa52484c.8eb1f6e7.js rename to assets/js/aa52484c.6a6d21da.js index 154bc34aec..ebaef1a639 100644 --- a/assets/js/aa52484c.8eb1f6e7.js +++ b/assets/js/aa52484c.6a6d21da.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2559],{8420:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-4.0/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.0/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/4.0/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/universal_service_providers.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-4.0/docs",previous:{title:"Laravel package",permalink:"/docs/4.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2559],{8420:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-4.0/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-4.0/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/4.0/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/universal_service_providers.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-4.0/docs",previous:{title:"Laravel package",permalink:"/docs/4.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/4.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/aa5b6080.0c74d9f2.js b/assets/js/aa5b6080.d0411448.js similarity index 99% rename from assets/js/aa5b6080.0c74d9f2.js rename to assets/js/aa5b6080.d0411448.js index 2206bfa4eb..883f5ab2e8 100644 --- a/assets/js/aa5b6080.0c74d9f2.js +++ b/assets/js/aa5b6080.d0411448.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3445],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},5080:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},s=void 0,u={unversionedId:"queries",id:"version-4.1/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.1/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.1/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/queries.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-4.1/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.1/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.1/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...o}=e;return(0,r.kt)(h,(0,a.Z)({},d,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3445],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},5080:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},s=void 0,u={unversionedId:"queries",id:"version-4.1/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.1/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.1/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/queries.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-4.1/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.1/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.1/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...o}=e;return(0,r.kt)(h,(0,a.Z)({},d,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/aa675676.72889597.js b/assets/js/aa675676.ffcd78b5.js similarity index 99% rename from assets/js/aa675676.72889597.js rename to assets/js/aa675676.ffcd78b5.js index f025b8a8b8..0c870eac01 100644 --- a/assets/js/aa675676.72889597.js +++ b/assets/js/aa675676.ffcd78b5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5075],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},765:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},s=void 0,u={unversionedId:"validation",id:"version-4.1/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.1/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.1/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/validation.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},sidebar:"version-4.1/docs",previous:{title:"Error handling",permalink:"/docs/4.1/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.1/authentication_authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5075],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function v(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=h({queryString:a,groupId:n}),[p,v]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,d.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??p;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),v(e)}),[u,v,i]),tabValues:i}}var f=a(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=v(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",y.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},765:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},s=void 0,u={unversionedId:"validation",id:"version-4.1/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-4.1/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/4.1/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/validation.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation",original_id:"validation"},sidebar:"version-4.1/docs",previous:{title:"Error handling",permalink:"/docs/4.1/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/4.1/authentication_authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3}],c={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,r.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,r.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.kt)("li",{parentName:"ul"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,r.kt)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,r.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"UserController.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\Graphqlite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"User.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,r.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,r.kt)("p",null,"If the data entered by the user is ",(0,r.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\Graphqlite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,r.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.kt)("p",null,"You can also pass an array to the ",(0,r.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ac8293fa.7512ae64.js b/assets/js/ac8293fa.ebfb9f4e.js similarity index 99% rename from assets/js/ac8293fa.7512ae64.js rename to assets/js/ac8293fa.ebfb9f4e.js index 9dadf37bbd..58a42a63f8 100644 --- a/assets/js/ac8293fa.7512ae64.js +++ b/assets/js/ac8293fa.ebfb9f4e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4369],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4267:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-6.0/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-6.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/6.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/README.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4369],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4267:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-6.0/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-6.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/6.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/README.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/acbaac14.a33203d5.js b/assets/js/acbaac14.924c3730.js similarity index 99% rename from assets/js/acbaac14.a33203d5.js rename to assets/js/acbaac14.924c3730.js index f5a3017b3f..8535b25614 100644 --- a/assets/js/acbaac14.a33203d5.js +++ b/assets/js/acbaac14.924c3730.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7582],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},47:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.3/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.3/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.3/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/fine-grained-security.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-4.3/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.3/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.3/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7582],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},47:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.3/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.3/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.3/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/fine-grained-security.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-4.3/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.3/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.3/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ae0a12ed.244e5058.js b/assets/js/ae0a12ed.a0896775.js similarity index 99% rename from assets/js/ae0a12ed.244e5058.js rename to assets/js/ae0a12ed.a0896775.js index 0c4fddab5e..a24905ffa1 100644 --- a/assets/js/ae0a12ed.244e5058.js +++ b/assets/js/ae0a12ed.a0896775.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2117],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},6065:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.2/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.2/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.2/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/fine-grained-security.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-4.2/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.2/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.2/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2117],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},6065:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.2/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.2/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.2/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/fine-grained-security.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-4.2/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.2/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.2/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/aebf35b6.129545d5.js b/assets/js/aebf35b6.50727791.js similarity index 99% rename from assets/js/aebf35b6.129545d5.js rename to assets/js/aebf35b6.50727791.js index 36fb28d40e..bae553b373 100644 --- a/assets/js/aebf35b6.129545d5.js +++ b/assets/js/aebf35b6.50727791.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5820],{1308:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/multiple_output_types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},sidebar:"version-4.0/docs",previous:{title:"Extending an input type",permalink:"/docs/4.0/extend_input_type"},next:{title:"Symfony specific features",permalink:"/docs/4.0/symfony-bundle-advanced"}},u={},s=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:s},r="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(r,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,i.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("h2",{id:"example"},"Example"),(0,i.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(Product $product): string\n {\n return $product->getName();\n }\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares a ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/external_type_declaration"},'"external" type')," mapping the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("p",null,"First of all, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,i.kt)("p",null,"Then, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.kt)("p",null,"Finally, we can write our requests:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')),(0,i.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.kt)("p",null,"Is a result, when the end user calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.kt)("p",null,"If you want to extend a type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.kt)("p",null,"So instead of writing:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"you will write:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')),(0,i.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5820],{1308:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var a=n(7462),i=(n(7294),n(3905));n(1839);const l={id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/multiple_output_types.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types",original_id:"multiple_output_types"},sidebar:"version-4.0/docs",previous:{title:"Extending an input type",permalink:"/docs/4.0/extend_input_type"},next:{title:"Symfony specific features",permalink:"/docs/4.0/symfony-bundle-advanced"}},u={},s=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:s},r="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(r,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("small",null,"Available in GraphQLite 4.0+"),(0,i.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,i.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("h2",{id:"example"},"Example"),(0,i.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(Product $product): string\n {\n return $product->getName();\n }\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares a ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/external_type_declaration"},'"external" type')," mapping the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.kt)("p",null,"First of all, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,i.kt)("p",null,"Then, we specify ",(0,i.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.kt)("p",null,"Finally, we can write our requests:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')),(0,i.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.kt)("p",null,"Is a result, when the end user calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.kt)("p",null,"If you want to extend a type using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.kt)("p",null,"So instead of writing:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"you will write:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')),(0,i.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b06c439f.d5f1c676.js b/assets/js/b06c439f.eadb4bfa.js similarity index 98% rename from assets/js/b06c439f.d5f1c676.js rename to assets/js/b06c439f.eadb4bfa.js index 7055e5aa33..b873727e0e 100644 --- a/assets/js/b06c439f.d5f1c676.js +++ b/assets/js/b06c439f.eadb4bfa.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3618],{908:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-4.3/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.3/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.3/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/internals.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-4.3/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.3/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.3/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.3/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3618],{908:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-4.3/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.3/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.3/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/internals.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-4.3/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.3/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.3/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.3/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b0ed7ea5.5f3eee2b.js b/assets/js/b0ed7ea5.d76a41ce.js similarity index 99% rename from assets/js/b0ed7ea5.5f3eee2b.js rename to assets/js/b0ed7ea5.d76a41ce.js index 53673c93c6..97f25e7e6b 100644 --- a/assets/js/b0ed7ea5.5f3eee2b.js +++ b/assets/js/b0ed7ea5.d76a41ce.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[562],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},9691:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},u=void 0,s={unversionedId:"external_type_declaration",id:"version-4.1/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.1/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/4.1/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/external_type_declaration.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-4.1/docs",previous:{title:"Extending a type",permalink:"/docs/4.1/extend_type"},next:{title:"Input types",permalink:"/docs/4.1/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[562],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},9691:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},u=void 0,s={unversionedId:"external_type_declaration",id:"version-4.1/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.1/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/4.1/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/external_type_declaration.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-4.1/docs",previous:{title:"Extending a type",permalink:"/docs/4.1/extend_type"},next:{title:"Input types",permalink:"/docs/4.1/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b103c05a.cf4673ae.js b/assets/js/b103c05a.0fbb9d7e.js similarity index 99% rename from assets/js/b103c05a.cf4673ae.js rename to assets/js/b103c05a.0fbb9d7e.js index 387aabd197..21a27408c0 100644 --- a/assets/js/b103c05a.cf4673ae.js +++ b/assets/js/b103c05a.0fbb9d7e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6031],{8847:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/docs/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/next/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/annotations-reference.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/next/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Prefetch",id:"prefetch",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Cost",id:"cost",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"prefetch"},"@Prefetch"),(0,l.kt)("p",null,"Marks field parameter to be used for ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/prefetch-method"},"prefetching"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"callable"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"callable"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the prefetch method (in same class) or a full callable, either a static method or regular service from the container")))),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("div",{class:"alert alert--warning"},"This annotation only works when a Schema is used to handle exactly one use request. If you serve your GraphQL API from long-running standalone servers (like Laravel Octane, Swoole, RoadRunner etc) and share the same Schema instance between multiple requests, please avoid using @HideIfUnauthorized."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"cost"},"@Cost"),(0,l.kt)("p",null,"Sets complexity and multipliers on fields for ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"complexity")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"int"),(0,l.kt)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"multipliers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"defaultMultiplier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"int"),(0,l.kt)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6031],{8847:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>o,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"annotations-reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/docs/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/next/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/annotations-reference.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/next/semver"}},o={},d=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Type",id:"type",level:2},{value:"@ExtendType",id:"extendtype",level:2},{value:"@Input",id:"input",level:2},{value:"@Field",id:"field",level:2},{value:"@SourceField",id:"sourcefield",level:2},{value:"@MagicField",id:"magicfield",level:2},{value:"@Prefetch",id:"prefetch",level:2},{value:"@Logged",id:"logged",level:2},{value:"@Right",id:"right",level:2},{value:"@FailWith",id:"failwith",level:2},{value:"@HideIfUnauthorized",id:"hideifunauthorized",level:2},{value:"@InjectUser",id:"injectuser",level:2},{value:"@Security",id:"security",level:2},{value:"@Factory",id:"factory",level:2},{value:"@UseInputType",id:"useinputtype",level:2},{value:"@Decorate",id:"decorate",level:2},{value:"@Autowire",id:"autowire",level:2},{value:"@HideParameter",id:"hideparameter",level:2},{value:"@Cost",id:"cost",level:2},{value:"@Validate",id:"validate",level:2},{value:"@Assertion",id:"assertion",level:2},{value:"@EnumType",id:"enumtype",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query"},"@Query"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation"},"@Mutation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type"},"@Type"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type. This is used with standard output\ntypes, as well as enum types. For input types, use the ",(0,l.kt)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.kt)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class/enum for the actual type. If no "class" attribute is passed, the type applies to the current class/enum. The current class/enum is assumed to be an entity (not service). If the "class" attribute ',(0,l.kt)("em",{parentName:"td"},"is passed"),", ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"the class/enum annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype"},"@ExtendType"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/extend-type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"input"},"@Input"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL input type generated. If not passed, the name of the class with suffix "Input" is used. If the class ends with "Input", the "Input" suffix is not added.')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," ",(0,l.kt)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," when ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"update"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.kt)("inlineCode",{parentName:"td"},"true")," all input fields will become optional and won't have default values thus won't be set on resolve if they are not specified in the query/mutation. This primarily applies to nullable fields.")))),(0,l.kt)("h2",{id:"field"},"@Field"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),".\nWhen it's applied on private or protected property, public getter or/and setter method is expected in the class accordingly\nwhether it's used for output type or input type. For example if property name is ",(0,l.kt)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.kt)("inlineCode",{parentName:"p"},"setFoo($foo)"),". Setter can be omitted if property related to the field is present in the constructor with the same name."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"for"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string, array"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the field to be used only for specific output or input type(s). By default field is used for all possible declared types.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/input-types"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.kt)("h2",{id:"sourcefield"},"@SourceField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment of the method in the source class is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield"},"@MagicField"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"description"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"sourceName"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.kt)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"prefetch"},"@Prefetch"),(0,l.kt)("p",null,"Marks field parameter to be used for ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/prefetch-method"},"prefetching"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"callable"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"callable"),(0,l.kt)("td",{parentName:"tr",align:null},"Name of the prefetch method (in same class) or a full callable, either a static method or regular service from the container")))),(0,l.kt)("h2",{id:"logged"},"@Logged"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right"},"@Right"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith"},"@FailWith"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.kt)("div",{class:"alert alert--warning"},"This annotation only works when a Schema is used to handle exactly one use request. If you serve your GraphQL API from long-running standalone servers (like Laravel Octane, Swoole, RoadRunner etc) and share the same Schema instance between multiple requests, please avoid using @HideIfUnauthorized."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser"},"@InjectUser"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security"},"@Security"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory"},"@Factory"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"/docs/next/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate"},"@Decorate"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire"},"@Autowire"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"cost"},"@Cost"),(0,l.kt)("p",null,"Sets complexity and multipliers on fields for ",(0,l.kt)("a",{parentName:"p",href:"/docs/next/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"complexity")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"int"),(0,l.kt)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"multipliers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"defaultMultiplier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"int"),(0,l.kt)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,l.kt)("h2",{id:"validate"},"@Validate"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion"},"@Assertion"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/next/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype"},(0,l.kt)("del",{parentName:"h2"},"@EnumType")),(0,l.kt)("p",null,(0,l.kt)("em",{parentName:"p"},"Deprecated: Use ",(0,l.kt)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,l.kt)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b26a5b84.9b387ff5.js b/assets/js/b26a5b84.e5f8e8c1.js similarity index 99% rename from assets/js/b26a5b84.9b387ff5.js rename to assets/js/b26a5b84.e5f8e8c1.js index dec8ae1cff..06cbc47b3b 100644 --- a/assets/js/b26a5b84.9b387ff5.js +++ b/assets/js/b26a5b84.e5f8e8c1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9136],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1185:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},s=void 0,u={unversionedId:"extend_type",id:"version-4.1/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.1/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/4.1/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/extend_type.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-4.1/docs",previous:{title:"Autowiring services",permalink:"/docs/4.1/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.1/external_type_declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9136],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1185:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},s=void 0,u={unversionedId:"extend_type",id:"version-4.1/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.1/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/4.1/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/extend_type.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-4.1/docs",previous:{title:"Autowiring services",permalink:"/docs/4.1/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.1/external_type_declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b2d9540a.ae7f82b4.js b/assets/js/b2d9540a.89e5221c.js similarity index 99% rename from assets/js/b2d9540a.ae7f82b4.js rename to assets/js/b2d9540a.89e5221c.js index 10e6398e3a..2ffb8bb5fb 100644 --- a/assets/js/b2d9540a.ae7f82b4.js +++ b/assets/js/b2d9540a.89e5221c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7990],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},2735:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),i=(a(7294),a(3905)),o=(a(1839),a(4866)),r=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-6.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/6.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/validation.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/6.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/6.0/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},h="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7990],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},2735:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(7462),i=(a(7294),a(3905)),o=(a(1839),a(4866)),r=a(5162);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-6.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/6.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/validation.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/6.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/6.0/authentication-authorization"}},d={},p=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},h="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n"))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n /**\n * @Mutation\n */\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")))),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n'))),(0,i.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n /**\n * @Assert\\Email(\n * message = "The email \'{{ value }}\' is not a valid email.",\n * checkMX = true\n * )\n */\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n * @Assert\\NotCompromisedPassword\n */\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')))),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b35d1284.1a39394f.js b/assets/js/b35d1284.c69f3805.js similarity index 97% rename from assets/js/b35d1284.1a39394f.js rename to assets/js/b35d1284.c69f3805.js index 8e0d4bdb11..7f616cddcd 100644 --- a/assets/js/b35d1284.1a39394f.js +++ b/assets/js/b35d1284.c69f3805.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9507],{4949:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-5.0/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-5.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/5.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/universal-service-providers.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-5.0/docs",previous:{title:"Laravel package",permalink:"/docs/5.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/5.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9507],{4949:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"version-5.0/universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-5.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/5.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/universal-service-providers.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"version-5.0/docs",previous:{title:"Laravel package",permalink:"/docs/5.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/5.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b370b50c.90bde699.js b/assets/js/b370b50c.7fdfaa6f.js similarity index 99% rename from assets/js/b370b50c.90bde699.js rename to assets/js/b370b50c.7fdfaa6f.js index 2f2cc6f202..d5cb158c4c 100644 --- a/assets/js/b370b50c.90bde699.js +++ b/assets/js/b370b50c.7fdfaa6f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9816],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9804:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-3.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-3.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/3.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/autowiring.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9816],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==l&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},9804:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),i=(a(1839),a(4866)),o=a(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-3.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-3.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/3.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/autowiring.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b42f5805.957ee956.js b/assets/js/b42f5805.771e0d34.js similarity index 99% rename from assets/js/b42f5805.957ee956.js rename to assets/js/b42f5805.771e0d34.js index 12a5f2927e..4114e9e99c 100644 --- a/assets/js/b42f5805.957ee956.js +++ b/assets/js/b42f5805.771e0d34.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4623],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},1349:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-4.3/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.3/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/4.3/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/external-type-declaration.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-4.3/docs",previous:{title:"Extending a type",permalink:"/docs/4.3/extend-type"},next:{title:"Input types",permalink:"/docs/4.3/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.3/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4623],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function d(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=u??p;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),y(e)}),[s,y,i]),tabValues:i}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(p(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},r,{className:(0,i.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",f.tabList)},o.createElement(b,(0,a.Z)({},e,t)),o.createElement(k,(0,a.Z)({},e,t)))}function v(e){const t=(0,g.Z)();return o.createElement(T,(0,a.Z)({key:String(t)},e))}},1349:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=n(7462),o=(n(7294),n(3905)),i=(n(1839),n(4866)),r=n(5162);const l={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},u=void 0,s={unversionedId:"external-type-declaration",id:"version-4.3/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.3/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/4.3/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/external-type-declaration.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"version-4.3/docs",previous:{title:"Extending a type",permalink:"/docs/4.3/extend-type"},next:{title:"Input types",permalink:"/docs/4.3/input-types"}},c={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,o.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")))),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')))),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n'))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')))),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.3/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n"))),(0,o.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b4657038.7b635e9e.js b/assets/js/b4657038.09de5a1b.js similarity index 98% rename from assets/js/b4657038.7b635e9e.js rename to assets/js/b4657038.09de5a1b.js index e05c2dfc89..c30937caeb 100644 --- a/assets/js/b4657038.7b635e9e.js +++ b/assets/js/b4657038.09de5a1b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1939],{4998:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-3.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-3.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/3.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/doctrine_annotations_attributes.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/3.0/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1939],{4998:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-3.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-3.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/3.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/doctrine_annotations_attributes.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/3.0/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b4aea2ce.c2a236ba.js b/assets/js/b4aea2ce.f5f04c00.js similarity index 98% rename from assets/js/b4aea2ce.c2a236ba.js rename to assets/js/b4aea2ce.f5f04c00.js index 01d8fd07ec..c7563663a5 100644 --- a/assets/js/b4aea2ce.c2a236ba.js +++ b/assets/js/b4aea2ce.f5f04c00.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8079],{1031:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},i=void 0,o={unversionedId:"laravel-package",id:"version-3.0/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.x.",source:"@site/versioned_docs/version-3.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/3.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/laravel-package.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-3.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/3.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/3.0/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2}],d={toc:s},c="wrapper";function h(e){let{components:a,...t}=e;return(0,r.kt)(c,(0,n.Z)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => '/graphql'\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing GraphQL Playground"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8079],{1031:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var n=t(7462),r=(t(7294),t(3905));t(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},i=void 0,o={unversionedId:"laravel-package",id:"version-3.0/laravel-package",title:"Getting started with Laravel",description:"The GraphQLite-Laravel package is compatible with Laravel 5.x.",source:"@site/versioned_docs/version-3.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/3.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/laravel-package.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package",original_id:"laravel-package"},sidebar:"version-3.0/docs",previous:{title:"Symfony bundle",permalink:"/docs/3.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/3.0/universal_service_providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2}],d={toc:s},c="wrapper";function h(e){let{components:a,...t}=e;return(0,r.kt)(c,(0,n.Z)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => '/graphql'\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing GraphQL Playground"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b5d0ac54.2a7c4b12.js b/assets/js/b5d0ac54.09e727dc.js similarity index 99% rename from assets/js/b5d0ac54.2a7c4b12.js rename to assets/js/b5d0ac54.09e727dc.js index 9f159e2ad3..41b0c48799 100644 --- a/assets/js/b5d0ac54.2a7c4b12.js +++ b/assets/js/b5d0ac54.09e727dc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6929],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7213:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-6.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-6.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/6.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/inheritance-interfaces.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/6.0/input-types"},next:{title:"Error handling",permalink:"/docs/6.0/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6929],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7213:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-6.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-6.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/6.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/inheritance-interfaces.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/6.0/input-types"},next:{title:"Error handling",permalink:"/docs/6.0/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b5d32d98.85cad965.js b/assets/js/b5d32d98.b700415a.js similarity index 96% rename from assets/js/b5d32d98.85cad965.js rename to assets/js/b5d32d98.b700415a.js index 985018ecce..75bbbf02e1 100644 --- a/assets/js/b5d32d98.85cad965.js +++ b/assets/js/b5d32d98.b700415a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4041],{2756:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>n,metadata:()=>r,toc:()=>p});var o=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},l=void 0,r={unversionedId:"file-uploads",id:"version-3.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-3.0/file_uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/3.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/file_uploads.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-3.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/3.0/inheritance"},next:{title:"Pagination",permalink:"/docs/3.0/pagination"}},s={},p=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,i.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.kt)("p",null,"In order to use this, you must first be sure that the ",(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.kt)("p",null,"Simply add ",(0,i.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,i.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,i.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.kt)("p",null,"See ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4041],{2756:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>n,metadata:()=>r,toc:()=>p});var o=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},l=void 0,r={unversionedId:"file-uploads",id:"version-3.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-3.0/file_uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/3.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/file_uploads.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-3.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/3.0/inheritance"},next:{title:"Pagination",permalink:"/docs/3.0/pagination"}},s={},p=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,i.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.kt)("p",null,"In order to use this, you must first be sure that the ",(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.kt)("p",null,"Simply add ",(0,i.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,i.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,i.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.kt)("p",null,"See ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b6a6a31f.fcb3b0f8.js b/assets/js/b6a6a31f.9deb08a6.js similarity index 98% rename from assets/js/b6a6a31f.fcb3b0f8.js rename to assets/js/b6a6a31f.9deb08a6.js index 34763a6444..319617cfb1 100644 --- a/assets/js/b6a6a31f.fcb3b0f8.js +++ b/assets/js/b6a6a31f.9deb08a6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5505],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},7758:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/docs/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/next/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/prefetch-method.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/next/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/next/automatic-persisted-queries"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/next/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field]\n public function getUser(#[Prefetch("prefetchUsers")] $prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as first argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public static function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as first argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When a "#',"[Prefetch]",'" attribute is detected on a parameter of "@Field" annotation, the method is called automatically.\nThe prefetch callable must be one of the following:'),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.kt)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.kt)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch([OtherService::class, 'prefetchMethod'])]"),"\nThe first argument of the method is always an array of instances of the main type. It can return absolutely anything (mixed).")),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetch methods."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field]\n public function getComments(#[Prefetch("prefetchComments")] $prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public static function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5505],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},7758:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/docs/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/next/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/prefetch-method.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/next/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/next/automatic-persisted-queries"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/next/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field]\n public function getUser(#[Prefetch("prefetchUsers")] $prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as first argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public static function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as first argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When a "#',"[Prefetch]",'" attribute is detected on a parameter of "@Field" annotation, the method is called automatically.\nThe prefetch callable must be one of the following:'),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.kt)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.kt)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.kt)("inlineCode",{parentName:"li"},"#[Prefetch([OtherService::class, 'prefetchMethod'])]"),"\nThe first argument of the method is always an array of instances of the main type. It can return absolutely anything (mixed).")),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetch methods."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field]\n public function getComments(#[Prefetch("prefetchComments")] $prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public static function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b7442939.6c0bd9aa.js b/assets/js/b7442939.5a65161b.js similarity index 98% rename from assets/js/b7442939.6c0bd9aa.js rename to assets/js/b7442939.5a65161b.js index 0e17dba749..1cc5ea5bbc 100644 --- a/assets/js/b7442939.6c0bd9aa.js +++ b/assets/js/b7442939.5a65161b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2998],{6824:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.3/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.3/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/argument-resolving.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.3/docs",previous:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2998],{6824:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.3/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.3/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/argument-resolving.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.3/docs",previous:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b8487569.14aa5627.js b/assets/js/b8487569.9ec8cb9a.js similarity index 99% rename from assets/js/b8487569.14aa5627.js rename to assets/js/b8487569.9ec8cb9a.js index ff4de90b2f..7afb82c86e 100644 --- a/assets/js/b8487569.14aa5627.js +++ b/assets/js/b8487569.9ec8cb9a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[593],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9402:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-4.3/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.3/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/4.3/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/extend-type.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-4.3/docs",previous:{title:"Autowiring services",permalink:"/docs/4.3/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.3/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[593],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},9402:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-4.3/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.3/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/4.3/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/extend-type.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-4.3/docs",previous:{title:"Autowiring services",permalink:"/docs/4.3/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.3/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b94a1068.6e820e03.js b/assets/js/b94a1068.c50458a0.js similarity index 99% rename from assets/js/b94a1068.6e820e03.js rename to assets/js/b94a1068.c50458a0.js index b0c3fa9c5e..12bb6c15b3 100644 --- a/assets/js/b94a1068.6e820e03.js +++ b/assets/js/b94a1068.c50458a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1886],{4170:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(7462),i=(t(7294),t(3905));t(1839);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-4.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/inheritance-interfaces.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},sidebar:"version-4.0/docs",previous:{title:"Input types",permalink:"/docs/4.0/input-types"},next:{title:"Error handling",permalink:"/docs/4.0/error-handling"}},p={},c=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],o={toc:c},d="wrapper";function m(e){let{components:n,...t}=e;return(0,i.kt)(d,(0,a.Z)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will translate in GraphQL schema as:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.kt)("p",null,"Please note that you do not need to put the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.kt)("p",null,"You don't have to explicitly put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")),(0,i.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,i.kt)("p",null,"In the example above, because the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1886],{4170:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(7462),i=(t(7294),t(3905));t(1839);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-4.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/inheritance-interfaces.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces",original_id:"inheritance-interfaces"},sidebar:"version-4.0/docs",previous:{title:"Input types",permalink:"/docs/4.0/input-types"},next:{title:"Error handling",permalink:"/docs/4.0/error-handling"}},p={},c=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],o={toc:c},d="wrapper";function m(e){let{components:n,...t}=e;return(0,i.kt)(d,(0,a.Z)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,i.kt)("p",null,"Let's say you have two classes, ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")),(0,i.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.kt)("p",null,"Written in ",(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,i.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.kt)("p",null,"The GraphQL ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("p",null,"This will translate in GraphQL schema as:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.kt)("p",null,"Please note that you do not need to put the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.kt)("p",null,"You don't have to explicitly put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")),(0,i.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,i.kt)("p",null,"In the example above, because the ",(0,i.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b9d6d6e5.7b7005ce.js b/assets/js/b9d6d6e5.145a6fb6.js similarity index 98% rename from assets/js/b9d6d6e5.7b7005ce.js rename to assets/js/b9d6d6e5.145a6fb6.js index 339a2ff78a..9d5c286a56 100644 --- a/assets/js/b9d6d6e5.7b7005ce.js +++ b/assets/js/b9d6d6e5.145a6fb6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2808],{2386:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.0/migrating",title:"Migrating",description:"Migrating from v3.0 to v4.0",source:"@site/versioned_docs/version-4.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/migrating.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},sidebar:"version-4.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.0/troubleshooting"},next:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"}},s={},d=[{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],u={toc:d},p="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(p,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/annotations_reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2808],{2386:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.0/migrating",title:"Migrating",description:"Migrating from v3.0 to v4.0",source:"@site/versioned_docs/version-4.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/migrating.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating",original_id:"migrating"},sidebar:"version-4.0/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.0/troubleshooting"},next:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"}},s={},d=[{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],u={toc:d},p="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(p,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/annotations_reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b9ea999a.69e00773.js b/assets/js/b9ea999a.55231b9f.js similarity index 99% rename from assets/js/b9ea999a.69e00773.js rename to assets/js/b9ea999a.55231b9f.js index 0ab15dd5d9..136239f2ee 100644 --- a/assets/js/b9ea999a.69e00773.js +++ b/assets/js/b9ea999a.55231b9f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8270],{179:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.1/annotations_reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.1/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.1/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/annotations_reference.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.1/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"http://localhost:3000/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8270],{179:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.1/annotations_reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.1/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.1/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/annotations_reference.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.1/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.kt)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #SourceField PHP 8 attribute)')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here. Available in Doctrine annotations only (not available in the #MagicField PHP 8 attribute)')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"value"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"http://localhost:3000/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.1/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ba7653ad.f135875a.js b/assets/js/ba7653ad.b15d10e5.js similarity index 98% rename from assets/js/ba7653ad.f135875a.js rename to assets/js/ba7653ad.b15d10e5.js index 6d2d342025..4db708a7f0 100644 --- a/assets/js/ba7653ad.f135875a.js +++ b/assets/js/ba7653ad.b15d10e5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[152],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},3587:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.3/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.3/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.3/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/file-uploads.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-4.3/docs",previous:{title:"Prefetching records",permalink:"/docs/4.3/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.3/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[152],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},3587:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.3/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.3/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.3/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/file-uploads.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-4.3/docs",previous:{title:"Prefetching records",permalink:"/docs/4.3/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.3/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bb5ef1b7.b95a59ce.js b/assets/js/bb5ef1b7.ad212a40.js similarity index 99% rename from assets/js/bb5ef1b7.b95a59ce.js rename to assets/js/bb5ef1b7.ad212a40.js index a7b83ddfcb..5ee57acefc 100644 --- a/assets/js/bb5ef1b7.b95a59ce.js +++ b/assets/js/bb5ef1b7.ad212a40.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3742],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1310:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-6.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-6.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/6.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/autowiring.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/6.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/6.0/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3742],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,i]),tabValues:i}}var g=n(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1310:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-6.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-6.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/6.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/autowiring.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/6.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/6.0/extend-type"}},c={},d=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.kt)("p",null,"Most of the time, your ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,r.kt)("h2",{id:"sample"},"Sample"),(0,r.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(\n #[Autowire]\n TranslatorInterface $translator\n ): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")))),(0,r.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,r.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.kt)("h2",{id:"best-practices"},"Best practices"),(0,r.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,r.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,r.kt)("pre",null,(0,r.kt)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,r.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,r.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,r.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,r.kt)("a",{parentName:"p",href:"extend-type"},"how to extend a type"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bb9fe7c3.b1275489.js b/assets/js/bb9fe7c3.fe9e89d6.js similarity index 99% rename from assets/js/bb9fe7c3.b1275489.js rename to assets/js/bb9fe7c3.fe9e89d6.js index db74b41576..47fd9578df 100644 --- a/assets/js/bb9fe7c3.b1275489.js +++ b/assets/js/bb9fe7c3.fe9e89d6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4446],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},7253:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var n=a(7462),i=(a(7294),a(3905));a(1839),a(4866),a(5162);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={unversionedId:"validation",id:"version-6.1/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.1/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/validation.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/authentication-authorization"}},s={},u=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(p,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4446],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),i=a(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),i=a(7294),o=a(6010),r=a(2466),l=a(6550),s=a(1980),u=a(7392),d=a(12);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:i}}=e;return{value:t,label:a,attributes:n,default:i}}))}function c(e){const{values:t,children:a}=e;return(0,i.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function y(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[p,y]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Nk)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),v=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{v&&l(v)}),[v]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,o]),tabValues:o}}var v=a(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=d.indexOf(e.currentTarget)+1;t=d[a]??d[0];break}case"ArrowLeft":{const a=d.indexOf(e.currentTarget)-1;t=d[a]??d[d.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:h,onClick:c},r,{className:(0,o.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),a??t)})))}function g(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=y(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},i.createElement(b,(0,n.Z)({},e,t)),i.createElement(g,(0,n.Z)({},e,t)))}function w(e){const t=(0,v.Z)();return i.createElement(k,(0,n.Z)({key:String(t)},e))}},7253:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var n=a(7462),i=(a(7294),a(3905));a(1839),a(4866),a(5162);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={unversionedId:"validation",id:"version-6.1/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.1/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/validation.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/authentication-authorization"}},s={},u=[{value:"Validating user input with Laravel",id:"validating-user-input-with-laravel",level:2},{value:"Validating user input with Symfony validator",id:"validating-user-input-with-symfony-validator",level:2},{value:"Using the Symfony validator bridge",id:"using-the-symfony-validator-bridge",level:3},{value:"Using the validator directly on a query / mutation / factory ...",id:"using-the-validator-directly-on-a-query--mutation--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(p,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.kt)("p",null,"However, it can integrate with your favorite framework validation mechanism. The way you validate user input will\ntherefore depend on the framework you are using."),(0,i.kt)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.kt)("p",null,"If you are using Laravel, jump directly to the ",(0,i.kt)("a",{parentName:"p",href:"/docs/laravel-package-advanced#support-for-laravel-validation-rules"},"GraphQLite Laravel package advanced documentation"),"\nto learn how to use the Laravel validation with GraphQLite."),(0,i.kt)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.kt)("p",null,"GraphQLite provides a bridge to use the ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("p",{parentName:"li"},'If you are using another framework, the "Symfony validator" component can be used in standalone mode. If you want to\nadd it to your project, you can require the ',(0,i.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.kt)("pre",{parentName:"li"},(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.kt)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.kt)("p",null,"Usually, when you use the Symfony validator component, you put annotations in your entities and you validate those entities\nusing the ",(0,i.kt)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="UserController.php"',title:'"UserController.php"'},"use Symfony\\Component\\Validator\\Validator\\ValidatorInterface;\nuse TheCodingMachine\\GraphQLite\\Validator\\ValidationFailedException\n\nclass UserController\n{\n private $validator;\n\n public function __construct(ValidatorInterface $validator)\n {\n $this->validator = $validator;\n }\n\n #[Mutation]\n public function createUser(string $email, string $password): User\n {\n $user = new User($email, $password);\n\n // Let's validate the user\n $errors = $this->validator->validate($user);\n\n // Throw an appropriate GraphQL exception if validation errors are encountered\n ValidationFailedException::throwException($errors);\n\n // No errors? Let's continue and save the user\n // ...\n }\n}\n")),(0,i.kt)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="User.php"',title:'"User.php"'},'use Symfony\\Component\\Validator\\Constraints as Assert;\n\nclass User\n{\n #[Assert\\Email(message: "The email \'{{ value }}\' is not a valid email.", checkMX: true)]\n private $email;\n\n /**\n * The NotCompromisedPassword assertion asks the "HaveIBeenPawned" service if your password has already leaked or not.\n */\n #[Assert\\NotCompromisedPassword]\n private $password;\n\n public function __construct(string $email, string $password)\n {\n $this->email = $email;\n $this->password = $password;\n }\n\n // ...\n}\n')),(0,i.kt)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email \'\\"foo@thisdomaindoesnotexistatall.com\\"\' is not a valid email.",\n "extensions": {\n "code": "bf447c1c-0266-4e10-9c6c-573df282e413",\n "field": "email",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.kt)("p",null,'If the data entered by the user is mapped to an object, please use the "validator" instance directly as explained in\nthe last chapter. It is a best practice to put your validation layer as close as possible to your domain model.'),(0,i.kt)("p",null,"If the data entered by the user is ",(0,i.kt)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.kt)("div",{class:"alert alert--warning"},"You generally don't want to do this. It is a best practice to put your validation constraints on your domain objects. Only use this technique if you want to validate user input and user input will not be stored in a domain object."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\n\n/**\n * @Query\n * @Assertion(for="email", constraint=@Assert\\Email())\n */\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.kt)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.kt)("p",null,"You can also pass an array to the ",(0,i.kt)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.kt)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.kt)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.kt)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute. This offers a way to validate input types before they're available as a method parameter of your query and mutation controllers. This way, when you're using your query or mutation controllers, you can feel confident that your input type objects have already been validated."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("p",null,"It's important to note that this validation implementation does not validate input types created with a factory. If you are creating an input type with a factory, or using primitive parameters in your query/mutation controllers, you should be sure to validate these independently. This is strictly for input type objects."),(0,i.kt)("p",null,"You can use one of the framework validation libraries listed above or implement your own validation for these cases. If you're using input type objects for most all of your query and mutation controllers, then there is little additional validation concerns with regards to user input. There are many reasons why you should consider defaulting to an InputType object, as opposed to individual arguments, for your queries and mutations. This is just one additional perk.")),(0,i.kt)("p",null,"To get started with validation on input types defined by an ",(0,i.kt)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addControllerNamespace('App\\\\Controllers');\n$factory->addTypeNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.kt)("p",null,"Your input type validator must implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"interface InputTypeValidatorInterface\n{\n /**\n * Checks to see if the Validator is currently enabled.\n */\n public function isEnabled(): bool;\n\n /**\n * Performs the validation of the InputType.\n *\n * @param object $input The input type object to validate\n */\n public function validate(object $input): void;\n}\n")),(0,i.kt)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's annotation based validation in addition to some other custom validation logic. It's really up to you on how you wish to handle your own validation. The ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.kt)("p",null,"You'll notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.kt)("inlineCode",{parentName:"p"},"void")," return. The purpose here is to encourage you to throw an Exception or handle validation output however you best see fit. GraphQLite does it's best to stay out of your way and doesn't make attempts to handle validation output. You can, however, throw an instance of ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.kt)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.kt)("p",null,"Also available is the ",(0,i.kt)("inlineCode",{parentName:"p"},"isEnabled")," method. This method is checked before executing validation on an InputType being resolved. You can work out your own logic to selectively enable or disable validation through this method. In most cases, you can simply return ",(0,i.kt)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.kt)("p",null,"And that's it, now, anytime an input type is resolved, the validator will be executed on that input type immediately after it has been hydrated with user input."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bcb6471f.96899bc0.js b/assets/js/bcb6471f.8fdff316.js similarity index 98% rename from assets/js/bcb6471f.96899bc0.js rename to assets/js/bcb6471f.8fdff316.js index 0e9bf5e9d9..d17bb02412 100644 --- a/assets/js/bcb6471f.96899bc0.js +++ b/assets/js/bcb6471f.8fdff316.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2827],{8643:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.1/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.1/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-4.1/docs",previous:{title:"Getting Started",permalink:"/docs/4.1/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.1/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],d={toc:s},c="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Now, go to the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,r.kt)("p",null,"More advanced parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(7462),r=(n(7294),n(3905));n(1839);const l={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.1/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.1/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle",original_id:"symfony-bundle"},sidebar:"version-4.1/docs",previous:{title:"Getting Started",permalink:"/docs/4.1/getting-started"},next:{title:"Laravel package",permalink:"/docs/4.1/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],d={toc:s},c="wrapper";function u(e){let{components:t,...n}=e;return(0,r.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The GraphQLite bundle is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.kt)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.kt)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Now, go to the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n namespace:\n # The namespace(s) that will store your GraphQLite controllers.\n # It accept either a string or a list of strings.\n controllers: App\\GraphQLController\\\n # The namespace(s) that will store your GraphQL types and factories.\n # It accept either a string or a list of strings.\n types:\n - App\\Types\\\n - App\\Entity\\\n")),(0,r.kt)("p",null,"More advanced parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.kt)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.kt)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.kt)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-5.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-5.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/5.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/internals.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-5.0/docs",previous:{title:"Laravel specific features",permalink:"/docs/5.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/5.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/5.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[963],{9348:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-5.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-5.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/5.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/internals.md",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-5.0/docs",previous:{title:"Laravel specific features",permalink:"/docs/5.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/5.0/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/5.0/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bd2c4a98.9d486e84.js b/assets/js/bd2c4a98.7af535c4.js similarity index 99% rename from assets/js/bd2c4a98.9d486e84.js rename to assets/js/bd2c4a98.7af535c4.js index a0c6437947..474d15977c 100644 --- a/assets/js/bd2c4a98.9d486e84.js +++ b/assets/js/bd2c4a98.7af535c4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1173],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8358:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-4.3/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-4.3/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.3/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/other-frameworks.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-4.3/docs",previous:{title:"Universal service providers",permalink:"/docs/4.3/universal-service-providers"},next:{title:"Queries",permalink:"/docs/4.3/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1173],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8358:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-4.3/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-4.3/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.3/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/other-frameworks.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-4.3/docs",previous:{title:"Universal service providers",permalink:"/docs/4.3/universal-service-providers"},next:{title:"Queries",permalink:"/docs/4.3/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bda39da3.7ccd6c95.js b/assets/js/bda39da3.9feaa3b0.js similarity index 98% rename from assets/js/bda39da3.7ccd6c95.js rename to assets/js/bda39da3.9feaa3b0.js index e851d1e10f..f64f634304 100644 --- a/assets/js/bda39da3.7ccd6c95.js +++ b/assets/js/bda39da3.9feaa3b0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7403],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2350:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.3/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.3/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.3/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/query-plan.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-4.3/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.3/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.3/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7403],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2350:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.3/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.3/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.3/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/query-plan.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"version-4.3/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.3/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.3/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bdb33130.e3e2ea1c.js b/assets/js/bdb33130.3f6b3639.js similarity index 99% rename from assets/js/bdb33130.e3e2ea1c.js rename to assets/js/bdb33130.3f6b3639.js index 5ca093d0cf..fefa40257f 100644 --- a/assets/js/bdb33130.e3e2ea1c.js +++ b/assets/js/bdb33130.3f6b3639.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6972],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),s=n(6550),p=n(1980),c=n(7392),o=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function m(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[p,c]=h({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=c[n].value;a!==s&&(u(t),p(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},3210:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/docs/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/next/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/inheritance-interfaces.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/next/input-types"},next:{title:"Error handling",permalink:"/docs/next/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6972],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),s=n(6550),p=n(1980),c=n(7392),o=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function m(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[p,c]=h({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=c[n].value;a!==s&&(u(t),p(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},3210:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/docs/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/next/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/inheritance-interfaces.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/next/input-types"},next:{title:"Error handling",permalink:"/docs/next/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/be1f0304.a75227bc.js b/assets/js/be1f0304.09fe2006.js similarity index 99% rename from assets/js/be1f0304.a75227bc.js rename to assets/js/be1f0304.09fe2006.js index d70747c77a..c3b24349a5 100644 --- a/assets/js/be1f0304.a75227bc.js +++ b/assets/js/be1f0304.09fe2006.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7711],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1965:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-5.0/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-5.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/5.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/extend-type.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-5.0/docs",previous:{title:"Autowiring services",permalink:"/docs/5.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/5.0/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7711],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},1965:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-5.0/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-5.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/5.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/extend-type.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-5.0/docs",previous:{title:"Autowiring services",permalink:"/docs/5.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/5.0/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/beccb025.097798c3.js b/assets/js/beccb025.ac117a94.js similarity index 98% rename from assets/js/beccb025.097798c3.js rename to assets/js/beccb025.ac117a94.js index 4f2c372924..448f41ba4c 100644 --- a/assets/js/beccb025.097798c3.js +++ b/assets/js/beccb025.ac117a94.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[314],{8328:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},r=void 0,s={unversionedId:"pagination",id:"version-4.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/pagination.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-4.0/docs",previous:{title:"File uploads",permalink:"/docs/4.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.0/custom-types"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,i.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, the GraphQLite Laravel bundle ",(0,i.kt)("a",{href:"laravel-package-advanced"},"comes with its own pagination system"),"."),(0,i.kt)("h2",{id:"installation"},"Installation"),(0,i.kt)("p",null,"You will need to install the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"In your query, simply return a class that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.kt)("p",null,'The "count" field returns the ',(0,i.kt)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[314],{8328:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},r=void 0,s={unversionedId:"pagination",id:"version-4.0/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/pagination.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination",original_id:"pagination"},sidebar:"version-4.0/docs",previous:{title:"File uploads",permalink:"/docs/4.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.0/custom-types"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,n.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,i.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, the GraphQLite Laravel bundle ",(0,i.kt)("a",{href:"laravel-package-advanced"},"comes with its own pagination system"),"."),(0,i.kt)("h2",{id:"installation"},"Installation"),(0,i.kt)("p",null,"You will need to install the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"In your query, simply return a class that implements ",(0,i.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.kt)("p",null,'The "count" field returns the ',(0,i.kt)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bf2a5963.5bb02ebe.js b/assets/js/bf2a5963.5f2239f4.js similarity index 98% rename from assets/js/bf2a5963.5bb02ebe.js rename to assets/js/bf2a5963.5f2239f4.js index 752fb917e8..3085ff4284 100644 --- a/assets/js/bf2a5963.5bb02ebe.js +++ b/assets/js/bf2a5963.5f2239f4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[630],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5583:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-4.3/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.3/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.3/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/pagination.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-4.3/docs",previous:{title:"File uploads",permalink:"/docs/4.3/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.3/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[630],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5583:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-4.3/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.3/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.3/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/pagination.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-4.3/docs",previous:{title:"File uploads",permalink:"/docs/4.3/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.3/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c007fb39.06be5372.js b/assets/js/c007fb39.9a2bad32.js similarity index 99% rename from assets/js/c007fb39.06be5372.js rename to assets/js/c007fb39.9a2bad32.js index 42e95585d2..fac94a5974 100644 --- a/assets/js/c007fb39.06be5372.js +++ b/assets/js/c007fb39.9a2bad32.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3087],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},9428:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-6.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/6.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/error-handling.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/6.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3087],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function v(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},9428:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"version-6.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/6.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/error-handling.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/6.0/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/6.0/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c0fa6485.7219bd0c.js b/assets/js/c0fa6485.9e1178ac.js similarity index 98% rename from assets/js/c0fa6485.7219bd0c.js rename to assets/js/c0fa6485.9e1178ac.js index 10bd70eead..a4d169d9da 100644 --- a/assets/js/c0fa6485.7219bd0c.js +++ b/assets/js/c0fa6485.9e1178ac.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1989],{8406:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes",original_id:"doctrine-annotations-attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.1/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.1/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.1/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/doctrine_annotations_attributes.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes",original_id:"doctrine-annotations-attributes"},sidebar:"version-4.1/docs",previous:{title:"Migrating",permalink:"/docs/4.1/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.1/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1989],{8406:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes",original_id:"doctrine-annotations-attributes"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.1/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.1/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.1/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/doctrine_annotations_attributes.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes",original_id:"doctrine-annotations-attributes"},sidebar:"version-4.1/docs",previous:{title:"Migrating",permalink:"/docs/4.1/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.kt)(d,(0,a.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support.\nThis was the purpose of the ',(0,i.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"Please note that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.kt)("div",{class:"alert alert--info"},(0,i.kt)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.kt)("ul",null,(0,i.kt)("li",null,"PhpStorm via the ",(0,i.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.kt)("li",null,"Eclipse via the ",(0,i.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.kt)("li",null,"Netbeans has native support")),(0,i.kt)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.kt)("p",null,"The same code can be written this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.kt)("p",null,"They support the same attributes too."),(0,i.kt)("p",null,"A few notable differences:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,i.kt)("p",null,"Let's take an example with the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.1/autowiring"},(0,i.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 7+")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"PHP 8")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c10d4a63.4adfd255.js b/assets/js/c10d4a63.b5502b9a.js similarity index 99% rename from assets/js/c10d4a63.4adfd255.js rename to assets/js/c10d4a63.b5502b9a.js index adf25d4abc..5f9b4b9aa9 100644 --- a/assets/js/c10d4a63.4adfd255.js +++ b/assets/js/c10d4a63.b5502b9a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9811],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},7953:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-6.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/6.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/multiple-output-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9811],{5162:(e,t,a)=>{a.d(t,{Z:()=>r});var n=a(7294),l=a(6010);const u={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:a,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,l.Z)(u.tabItem,r),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),l=a(7294),u=a(6010),r=a(2466),i=a(6550),o=a(1980),p=a(7392),s=a(12);function d(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function c(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),u=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,o._X)(u),(0,l.useCallback)((e=>{if(!u)return;const t=new URLSearchParams(n.location.search);t.set(u,e),n.replace({...n.location,search:t.toString()})}),[u,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=c(e),[r,i]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:u}))),[o,p]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,u]=(0,s.Nk)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),y=(()=>{const e=o??d;return m({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),f(e)}),[p,f,u]),tabValues:u}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=s.indexOf(e.currentTarget)+1;t=s[a]??s[0];break}case"ArrowLeft":{const a=s.indexOf(e.currentTarget)-1;t=s[a]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,u.Z)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},r,{className:(0,u.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":i===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const u=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=u.find((e=>e.props.value===n));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},u.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return l.createElement("div",{className:(0,u.Z)("tabs-container",b.tabList)},l.createElement(k,(0,n.Z)({},e,t)),l.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return l.createElement(g,(0,n.Z)({key:String(t)},e))}},7953:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(7462),l=(a(7294),a(3905)),u=(a(1839),a(4866)),r=a(5162);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-6.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/6.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/multiple-output-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,l.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.kt)("p",null,"But in very specific cases, you may want to use different GraphQL output type for the same class.\nFor instance, depending on the context, you might want to prevent the user from accessing some fields of your object."),(0,l.kt)("p",null,'To do so, you need to create 2 output types for the same PHP class. You typically do this using the "default" attribute of the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("h2",{id:"example"},"Example"),(0,l.kt)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," details, I want to have access to all fields.\nBut for some reason, I don't want to expose the price field of a product if I query the list of all products."),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(class: Product::class, name: "LimitedProduct", default: false)]\n#[SourceField(name: "name")]\nclass LimitedProductType\n{\n // ...\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(class=Product::class, name="LimitedProduct", default=false)\n * @SourceField(name="name")\n */\nclass LimitedProductType\n{\n // ...\n}\n')))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.kt)("a",{parentName:"p",href:"/docs/6.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.kt)("p",null,"First of all, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},'name="LimitedProduct"'),'. This is useful to avoid having colliding names with the "Product" GraphQL output type\nthat is already declared.'),(0,l.kt)("p",null,"Then, we specify ",(0,l.kt)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.kt)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.kt)("p",null,"Finally, we can write our requests:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n */\n #[Field]\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @return Product[]\n */\n #[Field(outputType: "[LimitedProduct!]!")]\n public function getProducts(): array { /* ... */ }\n}\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'class ProductController\n{\n /**\n * This field will use the default type.\n *\n * @Field\n */\n public function getProduct(int $id): Product { /* ... */ }\n\n /**\n * Because we use the "outputType" attribute, this field will use the other type.\n *\n * @Field(outputType="[LimitedProduct!]!")\n * @return Product[]\n */\n public function getProducts(): array { /* ... */ }\n}\n')))),(0,l.kt)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.kt)("p",null,"Is a result, when the end user calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.kt)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.kt)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.kt)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.kt)("p",null,"If you want to extend a type using the ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.kt)("p",null,"So instead of writing:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.kt)("p",null,"you will write:"),(0,l.kt)(u.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.kt)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c1fe0282.8ee4eca6.js b/assets/js/c1fe0282.eab02ae3.js similarity index 99% rename from assets/js/c1fe0282.8ee4eca6.js rename to assets/js/c1fe0282.eab02ae3.js index b9aff1a3d2..51cf67f822 100644 --- a/assets/js/c1fe0282.8ee4eca6.js +++ b/assets/js/c1fe0282.eab02ae3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5722],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},566:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-5.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-5.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/5.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/other-frameworks.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-5.0/docs",previous:{title:"Universal service providers",permalink:"/docs/5.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/5.0/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5722],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>v});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),c=n(7392),p=n(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,c]=m({queryString:n,groupId:a}),[u,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),c(e),f(e)}),[c,f,o]),tabValues:o}}var y=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=c[n].value;a!==l&&(u(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function w(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(w,(0,a.Z)({},e,t)))}function v(e){const t=(0,y.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},566:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},s=void 0,c={unversionedId:"other-frameworks",id:"version-5.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-5.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/5.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/other-frameworks.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},sidebar:"version-5.0/docs",previous:{title:"Universal service providers",permalink:"/docs/5.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/5.0/queries"}},p={},u=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:u},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="src/Controllers/MyController.php"',title:'"src/Controllers/MyController.php"'},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/container.php"',title:'"config/container.php"'},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c275698c.d89cb04a.js b/assets/js/c275698c.9344294b.js similarity index 99% rename from assets/js/c275698c.d89cb04a.js rename to assets/js/c275698c.9344294b.js index 44b32c6fd7..de43f61cc7 100644 --- a/assets/js/c275698c.d89cb04a.js +++ b/assets/js/c275698c.9344294b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5745],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2417:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-4.2/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.2/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/4.2/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/extend-type.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-4.2/docs",previous:{title:"Autowiring services",permalink:"/docs/4.2/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.2/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5745],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),i=n(2466),o=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==o&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(y,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},2417:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),i=n(5162);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-4.2/extend-type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-4.2/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/4.2/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/extend-type.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"version-4.2/docs",previous:{title:"Autowiring services",permalink:"/docs/4.2/autowiring"},next:{title:"External type declaration",permalink:"/docs/4.2/external-type-declaration"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,r.kt)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getId(): string\n {\n return $this->id;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,r.kt)("p",null,"Using ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[ExtendType(class: Product::class)]\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n #[Field]\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")))),(0,r.kt)("p",null,"Let's break this sample:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.kt)("p",null,"With the ",(0,r.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,r.kt)("p",null,'Using the "',(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c329487f.4e1c634c.js b/assets/js/c329487f.7af6fe0e.js similarity index 98% rename from assets/js/c329487f.4e1c634c.js rename to assets/js/c329487f.7af6fe0e.js index fcf3cc7eba..17730904dd 100644 --- a/assets/js/c329487f.4e1c634c.js +++ b/assets/js/c329487f.7af6fe0e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[45],{2360:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},o=void 0,l={unversionedId:"changelog",id:"version-4.0/changelog",title:"Changelog",description:"4.0",source:"@site/versioned_docs/version-4.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/CHANGELOG.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},sidebar:"version-4.0/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.0/semver"}},s={},p=[{value:"4.0",id:"40",level:2}],d={toc:p},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"40"},"4.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/error-handling"},"GraphQL errors")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.kt)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can map ",(0,i.kt)("a",{parentName:"li",href:"input-types#declaring-several-input-types-for-the-same-php-class"},"a given PHP class to several PHP input types")," (a PHP class can have several ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/extend_input_type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("p",null,"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("p",null,"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("p",null,"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[45],{2360:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},o=void 0,l={unversionedId:"changelog",id:"version-4.0/changelog",title:"Changelog",description:"4.0",source:"@site/versioned_docs/version-4.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/CHANGELOG.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},sidebar:"version-4.0/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.0/semver"}},s={},p=[{value:"4.0",id:"40",level:2}],d={toc:p},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"40"},"4.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/error-handling"},"GraphQL errors")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.kt)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can map ",(0,i.kt)("a",{parentName:"li",href:"input-types#declaring-several-input-types-for-the-same-php-class"},"a given PHP class to several PHP input types")," (a PHP class can have several ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/extend_input_type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("p",null,"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("p",null,"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("p",null,"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c3701568.ddede7ed.js b/assets/js/c3701568.5549601e.js similarity index 97% rename from assets/js/c3701568.ddede7ed.js rename to assets/js/c3701568.5549601e.js index 313c564b4d..f0d875a9c4 100644 --- a/assets/js/c3701568.ddede7ed.js +++ b/assets/js/c3701568.5549601e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8165],{3096:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(7462),a=(i(7294),i(3905));i(1839);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},r=void 0,s={unversionedId:"autowiring",id:"version-4.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/autowiring.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.0/docs",previous:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.0/extend_type"}},l={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.kt)(d,(0,n.Z)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.kt)("p",null,"Most of the time, your ",(0,a.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,a.kt)("h2",{id:"sample"},"Sample"),(0,a.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,a.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")),(0,a.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,a.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.kt)("h2",{id:"best-practices"},"Best practices"),(0,a.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,a.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.kt)("pre",null,(0,a.kt)("code",null," /** * @Field() */ public function getName(MyTranslator $translator): string"))),(0,a.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,a.kt)("pre",null,(0,a.kt)("code",null," /** * @Field() */ public function getName(TranslatorInterface $translator): string"))),(0,a.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')),(0,a.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,a.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,a.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,a.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,a.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8165],{3096:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(7462),a=(i(7294),i(3905));i(1839);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},r=void 0,s={unversionedId:"autowiring",id:"version-4.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-4.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/4.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/autowiring.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.0/docs",previous:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.0/extend_type"}},l={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.kt)(d,(0,n.Z)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.kt)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.kt)("p",null,"Most of the time, your ",(0,a.kt)("inlineCode",{parentName:"p"},"@Type")," annotation will be put on a model. And models do not have access to services.\nHopefully, if you add a type-hinted service in your field's declaration, GraphQLite will automatically fill it with\nthe service instance."),(0,a.kt)("h2",{id:"sample"},"Sample"),(0,a.kt)("p",null,"Let's assume you are running an international store. You have a ",(0,a.kt)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Autowire;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\nuse Symfony\\Component\\Translation\\TranslatorInterface;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n * @Autowire(for=\"$translator\")\n */\n public function getName(TranslatorInterface $translator): string\n {\n return $translator->trans('product_name_'.$this->id);\n }\n}\n")),(0,a.kt)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.kt)("div",{class:"alert alert--warning"},"As with most autowiring solutions, GraphQLite assumes that the service identifier in the container is the fully qualified class name of the type-hint. So in the example above, GraphQLite will look for a service whose name is ",(0,a.kt)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.kt)("h2",{id:"best-practices"},"Best practices"),(0,a.kt)("p",null,"It is a good idea to refrain from type-hinting on concrete implementations.\nMost often, your field declaration will be in your model. If you add a type-hint on a service, you are binding your domain\nwith a particular service implementation. This makes your code tightly coupled and less testable."),(0,a.kt)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.kt)("pre",null,(0,a.kt)("code",null," /** * @Field() */ public function getName(MyTranslator $translator): string"))),(0,a.kt)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.kt)("div",{class:"alert alert--success"},"Do this instead:",(0,a.kt)("pre",null,(0,a.kt)("code",null," /** * @Field() */ public function getName(TranslatorInterface $translator): string"))),(0,a.kt)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.kt)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.kt)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')),(0,a.kt)("div",{class:"alert alert--danger"},"While GraphQLite offers the possibility to specify the name of the service to be autowired, we would like to emphasize that this is ",(0,a.kt)("strong",null,"highly discouraged"),'. Hard-coding a container identifier in the code of your class is akin to using the "service locator" pattern, which is known to be an anti-pattern. Please refrain from doing this as much as possible.'),(0,a.kt)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.kt)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"Your service identifier in the container is not the fully qualified class name of the service (this is often true if you are not using a container supporting autowiring)"),(0,a.kt)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.kt)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.kt)("p",null,"If you do not want to use autowiring and if you still need to access services to compute a field, please read on\nthe next chapter to learn ",(0,a.kt)("a",{parentName:"p",href:"extend_type"},"how to extend a type"),"."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c4d37b36.ecc9e476.js b/assets/js/c4d37b36.c99dbb44.js similarity index 98% rename from assets/js/c4d37b36.ecc9e476.js rename to assets/js/c4d37b36.c99dbb44.js index c036d243a1..65396037b8 100644 --- a/assets/js/c4d37b36.ecc9e476.js +++ b/assets/js/c4d37b36.c99dbb44.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4265],{9146:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-6.1/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/argument-resolving.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4265],{9146:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-6.1/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.1/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/argument-resolving.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c5fa393d.e88c7eac.js b/assets/js/c5fa393d.3f51a552.js similarity index 98% rename from assets/js/c5fa393d.e88c7eac.js rename to assets/js/c5fa393d.3f51a552.js index 24983d0115..6f0839d8df 100644 --- a/assets/js/c5fa393d.e88c7eac.js +++ b/assets/js/c5fa393d.3f51a552.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1239],{9371:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},r=void 0,s={unversionedId:"authentication_authorization",id:"version-4.0/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.0/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/4.0/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/authentication_authorization.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-4.0/docs",previous:{title:"User input validation",permalink:"/docs/4.0/validation"},next:{title:"Fine grained security",permalink:"/docs/4.0/fine-grained-security"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],d={toc:l},h="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,i.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,i.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,i.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,i.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,i.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},(0,i.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,i.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,i.kt)("br",null),"See ",(0,i.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.kt)("h2",{id:"logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.kt)("p",null,"GraphQLite exposes two annotations (",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"In the example above, the query ",(0,i.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,i.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,i.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,i.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,i.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,i.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1239],{9371:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},r=void 0,s={unversionedId:"authentication_authorization",id:"version-4.0/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-4.0/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/4.0/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/authentication_authorization.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-4.0/docs",previous:{title:"User input validation",permalink:"/docs/4.0/validation"},next:{title:"Fine grained security",permalink:"/docs/4.0/fine-grained-security"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],d={toc:l},h="wrapper";function c(e){let{components:t,...n}=e;return(0,i.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,i.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,i.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,i.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,i.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,i.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},(0,i.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,i.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,i.kt)("br",null),"See ",(0,i.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.kt)("h2",{id:"logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.kt)("p",null,"GraphQLite exposes two annotations (",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"In the example above, the query ",(0,i.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,i.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,i.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,i.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,i.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,i.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c69dda99.c192c448.js b/assets/js/c69dda99.16b6bf92.js similarity index 99% rename from assets/js/c69dda99.c192c448.js rename to assets/js/c69dda99.16b6bf92.js index aea1538130..33e826f2b2 100644 --- a/assets/js/c69dda99.c192c448.js +++ b/assets/js/c69dda99.16b6bf92.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9297],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5930:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-4.2/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.2/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.2/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/README.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.2/docs",next:{title:"Getting Started",permalink:"/docs/4.2/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9297],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),u=a(2466),o=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function b(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=h({queryString:a,groupId:n}),[d,b]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),i(e),b(e)}),[i,b,l]),tabValues:l}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,l.Z)("tabs__item",g.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=b(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},5930:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),u=a(5162);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-4.2/index",title:"GraphQLite",description:"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers.",source:"@site/versioned_docs/version-4.2/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/4.2/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/README.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.2/docs",next:{title:"Getting Started",permalink:"/docs/4.2/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",{align:"center"},(0,r.kt)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.kt)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.kt)("h2",{id:"features"},"Features"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.kt)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.kt)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.kt)("h2",{id:"basic-example"},"Basic example"),(0,r.kt)("p",null,"First, declare a query in your controller:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ProductController\n{\n /**\n * @Query()\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"Then, annotate the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Product\n{\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type()\n */\nclass Product\n{\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n // ...\n}\n")))),(0,r.kt)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c7a4caa1.691e6048.js b/assets/js/c7a4caa1.86241355.js similarity index 98% rename from assets/js/c7a4caa1.691e6048.js rename to assets/js/c7a4caa1.86241355.js index c33752d31e..5115f3d25f 100644 --- a/assets/js/c7a4caa1.691e6048.js +++ b/assets/js/c7a4caa1.86241355.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9549],{847:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>v,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-3.0/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-3.0/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/3.0/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/universal_service_providers.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-3.0/docs",previous:{title:"Laravel package",permalink:"/docs/3.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/3.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function v(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and there is a ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"use Simplex\\Container;\nuse TheCodingMachine\\GraphQLite\\Schema;\nuse TheCodingMachine\\SymfonyCacheServiceProvider;\nuse TheCodingMachine\\DoctrineAnnotationsServiceProvider;\nuse TheCodingMachine\\GraphQLiteServiceProvider;\n\n$container = new Container([\n new SymfonyCacheServiceProvider(),\n new DoctrineAnnotationsServiceProvider,\n new GraphQLiteServiceProvider()]);\n$container->set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n")))}v.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9549],{847:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>v,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var t=i(7462),n=(i(7294),i(3905));i(1839);const a={id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},o=void 0,s={unversionedId:"universal_service_providers",id:"version-3.0/universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/versioned_docs/version-3.0/universal_service_providers.md",sourceDirName:".",slug:"/universal_service_providers",permalink:"/docs/3.0/universal_service_providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/universal_service_providers.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal_service_providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers",original_id:"universal_service_providers"},sidebar:"version-3.0/docs",previous:{title:"Laravel package",permalink:"/docs/3.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/3.0/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function v(e){let{components:r,...i}=e;return(0,n.kt)(d,(0,t.Z)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and there is a ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"composer.json")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre"},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("p",null,(0,n.kt)("strong",{parentName:"p"},"index.php")),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php"},"use Simplex\\Container;\nuse TheCodingMachine\\GraphQLite\\Schema;\nuse TheCodingMachine\\SymfonyCacheServiceProvider;\nuse TheCodingMachine\\DoctrineAnnotationsServiceProvider;\nuse TheCodingMachine\\GraphQLiteServiceProvider;\n\n$container = new Container([\n new SymfonyCacheServiceProvider(),\n new DoctrineAnnotationsServiceProvider,\n new GraphQLiteServiceProvider()]);\n$container->set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n")))}v.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c7e7ae18.733b58c5.js b/assets/js/c7e7ae18.44f9933c.js similarity index 99% rename from assets/js/c7e7ae18.733b58c5.js rename to assets/js/c7e7ae18.44f9933c.js index d635a6c146..359124dc91 100644 --- a/assets/js/c7e7ae18.733b58c5.js +++ b/assets/js/c7e7ae18.44f9933c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5574],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7904:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/docs/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/next/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/input-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/next/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/next/inheritance-interfaces"}},s={},c=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.kt)("a",{parentName:"p",href:"input-attribute"},(0,l.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,l.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.kt)("p",null,"Using the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var string|null\n */\n private ?string $name = null;\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call the ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,l.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,l.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.kt)("p",null,"Simple usage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,l.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.kt)("p",null,"You can add multiple ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /** @var int|null */\n protected $age;\n\n /**\n * @Field()\n * @param int|null $age\n */\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n')))),(0,l.kt)("p",null,"There are 2 input types added to the ",(0,l.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5574],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},7904:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/docs/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/next/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/input-types.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/next/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/next/inheritance-interfaces"}},s={},c=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.kt)("a",{parentName:"p",href:"input-attribute"},(0,l.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,l.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.kt)("p",null,"Using the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var string|null\n */\n private ?string $name = null;\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call the ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,l.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,l.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.kt)("p",null,"Simple usage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,l.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.kt)("p",null,"You can add multiple ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /** @var int|null */\n protected $age;\n\n /**\n * @Field()\n * @param int|null $age\n */\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n')))),(0,l.kt)("p",null,"There are 2 input types added to the ",(0,l.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c8bdc4df.fd752015.js b/assets/js/c8bdc4df.34e19a51.js similarity index 96% rename from assets/js/c8bdc4df.fd752015.js rename to assets/js/c8bdc4df.34e19a51.js index c4d766b100..756b18c29c 100644 --- a/assets/js/c8bdc4df.fd752015.js +++ b/assets/js/c8bdc4df.34e19a51.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2888],{5530:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>h,frontMatter:()=>n,metadata:()=>l,toc:()=>s});var o=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},r=void 0,l={unversionedId:"file-uploads",id:"version-4.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.0/file_uploads.md",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/file_uploads.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.0/docs",previous:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.0/pagination"}},p={},s=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,i.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.kt)("p",null,"In order to use this, you must first be sure that the ",(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.kt)("p",null,"Simply add ",(0,i.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,i.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,i.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.kt)("p",null,"See ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2888],{5530:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>h,frontMatter:()=>n,metadata:()=>l,toc:()=>s});var o=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},r=void 0,l={unversionedId:"file-uploads",id:"version-4.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.0/file_uploads.md",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/file_uploads.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.0/docs",previous:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.0/pagination"}},p={},s=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(d,(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.kt)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,i.kt)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.kt)("p",null,"In order to use this, you must first be sure that the ",(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.kt)("p",null,"Simply add ",(0,i.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.kt)("h2",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,i.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.kt)("h2",{id:"usage"},"Usage"),(0,i.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")),(0,i.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.kt)("p",null,"See ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c933a311.f4497fb8.js b/assets/js/c933a311.164393fe.js similarity index 99% rename from assets/js/c933a311.f4497fb8.js rename to assets/js/c933a311.164393fe.js index 6f01e91c60..e7e351ebe3 100644 --- a/assets/js/c933a311.f4497fb8.js +++ b/assets/js/c933a311.164393fe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6516],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function p(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,i]),tabValues:i}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},r,{className:(0,i.Z)("tabs__item",g.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},o.createElement(k,(0,a.Z)({},e,t)),o.createElement(b,(0,a.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return o.createElement(v,(0,a.Z)({key:String(t)},e))}},4354:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var a=n(7462),o=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={unversionedId:"external-type-declaration",id:"version-6.1/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-6.1/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/external-type-declaration.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/extend-type"},next:{title:"Input types",permalink:"/docs/input-types"}},s={},u=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,o.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n')),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6516],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),o=n(6010);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.Z)(i.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),o=n(7294),i=n(6010),r=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function d(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:o}}=e;return{value:t,label:n,attributes:a,default:o}}))}function p(e){const{values:t,children:n}=e;return(0,o.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(i),(0,o.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[r,l]=(0,o.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:n,groupId:a}),[d,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),y(e)}),[u,y,i]),tabValues:i}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},r,{className:(0,i.Z)("tabs__item",g.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,o.cloneElement)(e,{className:"margin-top--md"}):null}return o.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,o.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return o.createElement("div",{className:(0,i.Z)("tabs-container",g.tabList)},o.createElement(k,(0,a.Z)({},e,t)),o.createElement(b,(0,a.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return o.createElement(v,(0,a.Z)({key:String(t)},e))}},4354:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var a=n(7462),o=(n(7294),n(3905));n(1839),n(4866),n(5162);const i={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={unversionedId:"external-type-declaration",id:"version-6.1/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-6.1/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/external-type-declaration.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/extend-type"},next:{title:"Input types",permalink:"/docs/input-types"}},s={},u=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,o.kt)(d,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.kt)("p",null,"For instance:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,o.kt)("li",{parentName:"ul"},"etc.")),(0,o.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.kt)("p",null,"GraphQLite allows you to use a ",(0,o.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!")," The ",(0,o.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,o.kt)("br",null),(0,o.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,o.kt)("p",null,"In methods with a ",(0,o.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.kt)("h2",{id:"sourcefield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.kt)("p",null,"If you don't want to rewrite all ",(0,o.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price")]\nclass ProductType\n{\n}\n')),(0,o.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("h2",{id:"magicfield-annotation"},(0,o.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n#[Type]\n#[MagicField(name: "name", outputType: "String!")]\n#[MagicField(name: "price", outputType: "Float")]\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')),(0,o.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.kt)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.kt)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,o.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,o.kt)("p",null,"Any annotations described in the ",(0,o.kt)("a",{parentName:"p",href:"/docs/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.kt)("a",{parentName:"p",href:"/docs/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.kt)("div",{class:"alert alert--warning"},(0,o.kt)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.kt)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n#[Type(class: Product::class)]\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c953ec08.2ec7b349.js b/assets/js/c953ec08.450e2f30.js similarity index 99% rename from assets/js/c953ec08.2ec7b349.js rename to assets/js/c953ec08.450e2f30.js index f3d5eb88ee..25fbc0893d 100644 --- a/assets/js/c953ec08.2ec7b349.js +++ b/assets/js/c953ec08.450e2f30.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5073],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3304:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-5.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-5.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/5.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/mutations.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-5.0/docs",previous:{title:"Queries",permalink:"/docs/5.0/queries"},next:{title:"Type mapping",permalink:"/docs/5.0/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5073],{5162:(e,t,a)=>{a.d(t,{Z:()=>u});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:a,className:u}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,u),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),o=a(6010),u=a(2466),l=a(6550),s=a(1980),i=a(7392),c=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function p(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function b(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=p(e),[u,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,i]=b({queryString:a,groupId:n}),[d,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),f=(()=>{const e=s??d;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:u,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),i(e),h(e)}),[i,h,o]),tabValues:o}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,u.o5)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==l&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:p},u,{className:(0,o.Z)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=h(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",v.tabList)},r.createElement(g,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},3304:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),u=a(5162);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-5.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-5.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/5.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/mutations.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"version-5.0/docs",previous:{title:"Queries",permalink:"/docs/5.0/queries"},next:{title:"Type mapping",permalink:"/docs/5.0/type-mapping"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, mutations are created ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/queries"},"like queries"),"."),(0,r.kt)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Mutation]\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n"))),(0,r.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n /**\n * @Mutation\n */\n public function saveProduct(int $id, string $name, ?float $price = null): Product\n {\n // Some code that saves a product.\n }\n}\n")))))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ca36df4d.484ffd6d.js b/assets/js/ca36df4d.627fff1b.js similarity index 98% rename from assets/js/ca36df4d.484ffd6d.js rename to assets/js/ca36df4d.627fff1b.js index e15e92a629..1180765871 100644 --- a/assets/js/ca36df4d.484ffd6d.js +++ b/assets/js/ca36df4d.627fff1b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[917],{2197:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"changelog",title:"Changelog",description:"5.0.0",source:"@site/docs/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/next/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/CHANGELOG.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/next/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[917],{2197:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"changelog",title:"Changelog",description:"5.0.0",source:"@site/docs/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/next/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/CHANGELOG.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},d={},p=[{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/next/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/next/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/caa79efa.6c43f4db.js b/assets/js/caa79efa.1b7095a0.js similarity index 99% rename from assets/js/caa79efa.6c43f4db.js rename to assets/js/caa79efa.1b7095a0.js index d39b379c07..6324b228d8 100644 --- a/assets/js/caa79efa.6c43f4db.js +++ b/assets/js/caa79efa.1b7095a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9711],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},6747:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.3/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.3/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.3/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/custom-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-4.3/docs",previous:{title:"Pagination",permalink:"/docs/4.3/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9711],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},6747:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.3/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.3/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.3/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/custom-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-4.3/docs",previous:{title:"Pagination",permalink:"/docs/4.3/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cb01db44.d54c1a9c.js b/assets/js/cb01db44.b46217e8.js similarity index 99% rename from assets/js/cb01db44.d54c1a9c.js rename to assets/js/cb01db44.b46217e8.js index 820af0ccb4..00a22d872e 100644 --- a/assets/js/cb01db44.d54c1a9c.js +++ b/assets/js/cb01db44.b46217e8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2380],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7321:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-5.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-5.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/5.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/inheritance-interfaces.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-5.0/docs",previous:{title:"Input types",permalink:"/docs/5.0/input-types"},next:{title:"Error handling",permalink:"/docs/5.0/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2380],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},7321:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-5.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-5.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/5.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/inheritance-interfaces.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-5.0/docs",previous:{title:"Input types",permalink:"/docs/5.0/input-types"},next:{title:"Error handling",permalink:"/docs/5.0/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc08685c.cbfca237.js b/assets/js/cc08685c.a7406d7b.js similarity index 98% rename from assets/js/cc08685c.cbfca237.js rename to assets/js/cc08685c.a7406d7b.js index 59f6b77c53..93c4b50df9 100644 --- a/assets/js/cc08685c.cbfca237.js +++ b/assets/js/cc08685c.a7406d7b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1760],{3449:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-4.2/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.2/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.2/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/internals.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-4.2/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.2/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.2/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.2/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1760],{3449:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-4.2/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.2/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.2/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/internals.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"version-4.2/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.2/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.2/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.2/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc1c02fe.f473a573.js b/assets/js/cc1c02fe.a772bc02.js similarity index 99% rename from assets/js/cc1c02fe.f473a573.js rename to assets/js/cc1c02fe.a772bc02.js index 6d137bb4ad..646302cf67 100644 --- a/assets/js/cc1c02fe.f473a573.js +++ b/assets/js/cc1c02fe.a772bc02.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[288],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},7378:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-4.3/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.3/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.3/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/doctrine-annotations-attributes.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-4.3/docs",previous:{title:"Migrating",permalink:"/docs/4.3/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.3/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[288],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},7378:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-4.3/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.3/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.3/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/doctrine-annotations-attributes.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-4.3/docs",previous:{title:"Migrating",permalink:"/docs/4.3/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.3/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.3/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc1f18af.052fec8e.js b/assets/js/cc1f18af.c46f462f.js similarity index 99% rename from assets/js/cc1f18af.052fec8e.js rename to assets/js/cc1f18af.c46f462f.js index 6e54e9f437..3da3cae693 100644 --- a/assets/js/cc1f18af.052fec8e.js +++ b/assets/js/cc1f18af.c46f462f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[523],{9491:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-6.0/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/6.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/6.0/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[523],{9491:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-6.0/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/6.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/6.0/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cd25a595.4e9d497f.js b/assets/js/cd25a595.f4210a8e.js similarity index 98% rename from assets/js/cd25a595.4e9d497f.js rename to assets/js/cd25a595.f4210a8e.js index d7fd507167..3e3a0d4055 100644 --- a/assets/js/cd25a595.4e9d497f.js +++ b/assets/js/cd25a595.f4210a8e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1012],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4705:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.2/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.2/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.2/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/file-uploads.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-4.2/docs",previous:{title:"Prefetching records",permalink:"/docs/4.2/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.2/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1012],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4705:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-4.2/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-4.2/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/4.2/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/file-uploads.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-4.2/docs",previous:{title:"Prefetching records",permalink:"/docs/4.2/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.2/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cd30f404.68d7e3a8.js b/assets/js/cd30f404.c89e8722.js similarity index 99% rename from assets/js/cd30f404.68d7e3a8.js rename to assets/js/cd30f404.c89e8722.js index ae41ad8c88..fd0f475d65 100644 --- a/assets/js/cd30f404.68d7e3a8.js +++ b/assets/js/cd30f404.c89e8722.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7441],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},1669:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.1/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-4.1/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.1/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/laravel-package-advanced.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.1/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.1/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'```php\n/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7441],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},1669:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-4.1/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-4.1/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.1/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/laravel-package-advanced.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.1/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.1/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'```php\n/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cd699560.0331ffa8.js b/assets/js/cd699560.3905c5de.js similarity index 99% rename from assets/js/cd699560.0331ffa8.js rename to assets/js/cd699560.3905c5de.js index bddfb6c7a0..e2b066a13a 100644 --- a/assets/js/cd699560.0331ffa8.js +++ b/assets/js/cd699560.3905c5de.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9108],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},1834:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-4.2/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.2/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.2/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/doctrine-annotations-attributes.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-4.2/docs",previous:{title:"Migrating",permalink:"/docs/4.2/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.2/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9108],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>P});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),l=n(6550),s=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function m(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,l.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function b(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,l]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!m({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[s,u]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=s??p;return m({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!m({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);l(t),u(t),b(t)}),[u,b,o]),tabValues:o}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(t){let{className:e,block:n,selectedValue:l,selectValue:s,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==l&&(p(e),s(a))},m=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===e?0:-1,"aria-selected":l===e,key:e,ref:t=>c.push(t),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",k.tabItem,i?.className,{"tabs__item--active":l===e})}),n??e)})))}function v(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function y(t){const e=b(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(g,(0,a.Z)({},t,e)),r.createElement(v,(0,a.Z)({},t,e)))}function P(t){const e=(0,f.Z)();return r.createElement(y,(0,a.Z)({key:String(e)},t))}},1834:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const l={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},s=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-4.2/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.2/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.2/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/doctrine-annotations-attributes.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"version-4.2/docs",previous:{title:"Migrating",permalink:"/docs/4.2/migrating"},next:{title:"Annotations reference",permalink:"/docs/4.2/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],d={toc:p},m="wrapper";function h(t){let{components:e,...n}=t;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.2/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cddcd4e6.416c328f.js b/assets/js/cddcd4e6.07845102.js similarity index 99% rename from assets/js/cddcd4e6.416c328f.js rename to assets/js/cddcd4e6.07845102.js index 6df6461bc1..11629d3c04 100644 --- a/assets/js/cddcd4e6.416c328f.js +++ b/assets/js/cddcd4e6.07845102.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9212],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function m(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=m(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return d({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!d({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),m=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:m},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},8100:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-3.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/3.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],m={toc:p},d="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9212],{5162:(e,t,n)=>{n.d(t,{Z:()=>u});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,u),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>q});var a=n(7462),l=n(7294),r=n(6010),u=n(2466),o=n(6550),i=n(1980),s=n(7392),c=n(12);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function m(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=m(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=i??p;return d({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!d({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),g(e)}),[s,g,r]),tabValues:r}}var f=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.o5)(),m=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:m},u,{className:(0,r.Z)("tabs__item",y.tabItem,u?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",y.tabList)},l.createElement(b,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function q(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},8100:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),u=n(5162);const o={id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"},i=void 0,s={unversionedId:"symfony-bundle-advanced",id:"version-3.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/3.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],m={toc:p},d="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.kt)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.kt)("p",null,'Out of the box, the GraphQLite bundle will expose a "login" and a "logout" mutation as well\nas a "me" query (that returns the current user).'),(0,l.kt)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.kt)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.kt)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.kt)("p",null,"By settings ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=on"),", you are stating that you explicitly want the login/logout mutations.\nIf one of the dependencies is missing, an exception is thrown (unlike in default mode where the mutations\nare silently discarded)."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.kt)("p",null,'By default, GraphQLite assumes that your firewall name is "main". This is the default value used in the\nSymfony security bundle so it is likely the value you are using. If for some reason you want to use\nanother firewall, configure the name with ',(0,l.kt)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.kt)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.kt)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.kt)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.kt)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.kt)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.kt)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.kt)("p",null,"The mutation below will log-in a user:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.kt)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.kt)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.kt)("p",null,"In Symfony, user objects implement ",(0,l.kt)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.kt)("p",null,"If you want to get more fields, just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n #[Field]\n public function getEmail() : string\n {\n // ...\n }\n\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n /**\n * @Field\n */\n public function getEmail() : string\n {\n // ...\n }\n\n}\n")))),(0,l.kt)("p",null,"You can now query this field using an ",(0,l.kt)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.kt)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.kt)("p",null,'Use the "logout" mutation to log a user out'),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.kt)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.kt)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.kt)("p",null,"Most of the time, getting the request object is irrelevant. Indeed, it is GraphQLite's job to parse this request and\nmanage it for you. Sometimes yet, fetching the request can be needed. In those cases, simply type-hint on the request\nin any parameter of your query/mutation/field."),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(u.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n#[Query]\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n"))),(0,l.kt)(u.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"use Symfony\\Component\\HttpFoundation\\Request;\n\n/**\n * @Query\n */\npublic function getUser(int $id, Request $request): User\n{\n // The $request object contains the Symfony Request.\n}\n")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ce95b17c.f4c63794.js b/assets/js/ce95b17c.850e0c56.js similarity index 98% rename from assets/js/ce95b17c.f4c63794.js rename to assets/js/ce95b17c.850e0c56.js index 0af0893471..f5596981bf 100644 --- a/assets/js/ce95b17c.f4c63794.js +++ b/assets/js/ce95b17c.850e0c56.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9817],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function g(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(g,(0,a.Z)({key:String(t)},e))}},4273:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"query-plan",title:"Query plan",description:"The problem",source:"@site/docs/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/next/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/query-plan.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/next/operation-complexity"},next:{title:"Prefetching records",permalink:"/docs/next/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9817],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function g(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(g,(0,a.Z)({key:String(t)},e))}},4273:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"query-plan",title:"Query plan",description:"The problem",source:"@site/docs/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/next/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/query-plan.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/next/operation-complexity"},next:{title:"Prefetching records",permalink:"/docs/next/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d07ad772.03548c0a.js b/assets/js/d07ad772.dc754465.js similarity index 99% rename from assets/js/d07ad772.03548c0a.js rename to assets/js/d07ad772.dc754465.js index e1fc2a9d33..db7cf25161 100644 --- a/assets/js/d07ad772.03548c0a.js +++ b/assets/js/d07ad772.dc754465.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6005],{9225:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.3/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.3/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/laravel-package.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-4.3/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.3/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6005],{9225:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=a(7462),r=(a(7294),a(3905));a(1839);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-4.3/laravel-package",title:"Getting started with Laravel",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-4.3/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/4.3/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/laravel-package.md",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"version-4.3/docs",previous:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/4.3/universal-service-providers"}},p={},s=[{value:"Installation",id:"installation",level:2},{value:"Configuring CSRF protection",id:"configuring-csrf-protection",level:2},{value:"Use the api middleware",id:"use-the-api-middleware",level:3},{value:"Disable CSRF for the /graphql route",id:"disable-csrf-for-the-graphql-route",level:3},{value:"Configuring your GraphQL client",id:"configuring-your-graphql-client",level:3},{value:"Adding GraphQL DevTools",id:"adding-graphql-devtools",level:2},{value:"Troubleshooting HTTP 419 errors",id:"troubleshooting-http-419-errors",level:2}],h={toc:s},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.kt)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.kt)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.kt)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.kt)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.kt)("p",null,"You can then configure the library by editing ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => env('GRAPHQLITE_URI', '/graphql'),\n 'middleware' => ['web'],\n 'guard' => ['web'],\n];\n")),(0,r.kt)("p",null,"The debug parameters are detailed in the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/error-handling/"},"documentation of the Webonyx GraphQL library"),"\nwhich is used internally by GraphQLite."),(0,r.kt)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.kt)("div",{class:"alert alert--warning"},"By default, the ",(0,r.kt)("code",null,"/graphql")," route is placed under ",(0,r.kt)("code",null,"web")," middleware group which requires a",(0,r.kt)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.kt)("p",null,"You have 3 options:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Use the ",(0,r.kt)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.kt)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.kt)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.kt)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.kt)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.kt)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.kt)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,r.kt)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.kt)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.kt)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.kt)("p",null,"If you plan to use graphql from web browsers and if you want to explicitly allow access from external applications\n(through CORS headers), you need to disable the CSRF token."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.kt)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.kt)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.kt)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.kt)("p",null,"If you are planning to use ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql")," only from your website domain, then the safest way is to keep CSRF enabled and\nconfigure your GraphQL JS client to pass the CSRF headers on any graphql request."),(0,r.kt)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.kt)("p",null,"Assuming you are using ",(0,r.kt)("a",{parentName:"p",href:"https://www.apollographql.com/docs/link/links/http/"},"Apollo"),", you need to be sure that Apollo passes the token\nback to Laravel on every request."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js",metastring:'title="Sample Apollo client setup with CSRF support"',title:'"Sample',Apollo:!0,client:!0,setup:!0,with:!0,CSRF:!0,'support"':!0},"import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';\n\nconst httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });\n\nconst authLink = new ApolloLink((operation, forward) => {\n // Retrieve the authorization token from local storage.\n const token = localStorage.getItem('auth_token');\n\n // Get the XSRF-TOKEN that is set by Laravel on each request\n var cookieValue = document.cookie.replace(/(?:(?:^|.*;\\s*)XSRF-TOKEN\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n\n // Use the setContext method to set the X-CSRF-TOKEN header back.\n operation.setContext({\n headers: {\n 'X-CSRF-TOKEN': cookieValue\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink), // Chain it with the HttpLink\n cache: new InMemoryCache()\n});\n")),(0,r.kt)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.kt)("p",null,"GraphQLite does not include additional GraphQL tooling, such as the GraphiQL editor.\nTo integrate a web UI to query your GraphQL endpoint with your Laravel installation,\nwe recommend installing ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.kt)("p",null,"By default, the playground will be available at ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.kt)("p",null,"Or you can install ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.kt)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,r.kt)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.kt)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.kt)("p",null,"If HTTP requests to GraphQL endpoint generate responses with the HTTP 419 status code, you have an issue with the configuration of your\nCSRF token. Please check again ",(0,r.kt)("a",{parentName:"p",href:"#configuring-csrf-protection"},"the paragraph dedicated to CSRF configuration"),"."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d3540d59.05e6d0e3.js b/assets/js/d3540d59.85ed7083.js similarity index 99% rename from assets/js/d3540d59.05e6d0e3.js rename to assets/js/d3540d59.85ed7083.js index 03a22426fa..0b64a834b3 100644 --- a/assets/js/d3540d59.05e6d0e3.js +++ b/assets/js/d3540d59.85ed7083.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5676],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},4971:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.2/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.2/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.2/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/inheritance-interfaces.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-4.2/docs",previous:{title:"Input types",permalink:"/docs/4.2/input-types"},next:{title:"Error handling",permalink:"/docs/4.2/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5676],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},4971:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-4.2/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-4.2/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/4.2/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/inheritance-interfaces.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"version-4.2/docs",previous:{title:"Input types",permalink:"/docs/4.2/input-types"},next:{title:"Error handling",permalink:"/docs/4.2/error-handling"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d4446569.9f545396.js b/assets/js/d4446569.37e9c2d3.js similarity index 99% rename from assets/js/d4446569.9f545396.js rename to assets/js/d4446569.37e9c2d3.js index 124899d163..75a92cd04b 100644 --- a/assets/js/d4446569.9f545396.js +++ b/assets/js/d4446569.37e9c2d3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8835],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8366:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.2/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.2/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.2/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/custom-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-4.2/docs",previous:{title:"Pagination",permalink:"/docs/4.2/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8835],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const p={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(p.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),p=a(6010),o=a(2466),l=a(6550),s=a(1980),u=a(7392),i=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function y(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function d(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,l.k6)(),p=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(p),(0,r.useCallback)((e=>{if(!p)return;const t=new URLSearchParams(n.location.search);t.set(p,e),n.replace({...n.location,search:t.toString()})}),[p,n])]}function h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,p=y(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:p}))),[s,u]=m({queryString:a,groupId:n}),[c,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),f=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:p}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,p]),tabValues:p}}var f=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),y=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(c(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=i.indexOf(e.currentTarget)+1;t=i[a]??i[0];break}case"ArrowLeft":{const a=i.indexOf(e.currentTarget)-1;t=i[a]??i[i.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,p.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:y},o,{className:(0,p.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const p=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=p.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},p.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function T(e){const t=h(e);return r.createElement("div",{className:(0,p.Z)("tabs-container",g.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(T,(0,n.Z)({key:String(t)},e))}},8366:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),p=(a(1839),a(4866)),o=a(5162);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},s=void 0,u={unversionedId:"custom-types",id:"version-4.2/custom-types",title:"Custom types",description:"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite.",source:"@site/versioned_docs/version-4.2/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/4.2/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/custom-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"version-4.2/docs",previous:{title:"Pagination",permalink:"/docs/4.2/pagination"},next:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"}},i={},c=[{value:"Usage",id:"usage",level:2},{value:"Registering a custom output type (advanced)",id:"registering-a-custom-output-type-advanced",level:2},{value:"Symfony users",id:"symfony-users",level:3},{value:"Other frameworks",id:"other-frameworks",level:3},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],y={toc:c},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type(class: Product::class)]\nclass ProductType\n{\n #[Field]\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field\n */\n public function getId(Product $source): string\n {\n return $source->getId();\n }\n}\n")))),(0,r.kt)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.kt)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.kt)("inlineCode",{parentName:"p"},"string"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.kt)("p",null,"GraphQL comes with an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.kt)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.kt)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.kt)(p.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.kt)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.kt)("p",null,"In order to create a custom output type, you need to:"),(0,r.kt)("ol",null,(0,r.kt)("li",{parentName:"ol"},"Design a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.kt)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.kt)("p",null,"You'll find more details on the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,r.kt)("hr",null),(0,r.kt)("p",null,"In order to find existing types, the schema is using ",(0,r.kt)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.kt)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.kt)("p",null,"You need to make sure that one of these type mappers can return an instance of your type. The way you do this will depend on the framework\nyou use."),(0,r.kt)("h3",{id:"symfony-users"},"Symfony users"),(0,r.kt)("p",null,"Any class extending ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\ObjectType")," (and available in the container) will be automatically detected\nby Symfony and added to the schema."),(0,r.kt)("p",null,"If you want to automatically map the output type to a given PHP class, you will have to explicitly declare the output type\nas a service and use the ",(0,r.kt)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-yaml"},"# config/services.yaml\nservices:\n App\\MyOutputType:\n tags:\n - { name: 'graphql.output_type', class: 'App\\MyPhpClass' }\n")),(0,r.kt)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.kt)("p",null,"The easiest way is to use a ",(0,r.kt)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Sample code:\n$staticTypeMapper = new StaticTypeMapper();\n\n// Let's register a type that maps by default to the \"MyClass\" PHP class\n$staticTypeMapper->setTypes([\n MyClass::class => new MyCustomOutputType()\n]);\n\n// If you don't want your output type to map to any PHP class by default, use:\n$staticTypeMapper->setNotMappedTypes([\n new MyCustomOutputType()\n]);\n\n// Register the static type mapper in your application using the SchemaFactory instance\n$schemaFactory->addTypeMapper($staticTypeMapper);\n")),(0,r.kt)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.kt)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),'.\nIt contains a number of "out-of-the-box" scalar types ready to use and you might find what you need there.'),(0,r.kt)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.kt)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"create a ",(0,r.kt)("a",{parentName:"li",href:"https://webonyx.github.io/graphql-php/type-system/scalar-types/#writing-custom-scalar-types"},"Webonyx custom scalar type"),".\nYou do this by creating a class that extends ",(0,r.kt)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper" that will map PHP types to the GraphQL scalar type. You do this by writing a class implementing the ',(0,r.kt)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.kt)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface RootTypeMapperInterface\n{\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n /**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n\n public function mapNameToType(string $typeName): NamedType;\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," are meant to map a return type (for output types) or a parameter type (for input types)\nto your GraphQL scalar type. Return your scalar type if there is a match or ",(0,r.kt)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.kt)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.kt)("p",null,"RootTypeMapper are organized ",(0,r.kt)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class AnyScalarTypeMapper implements RootTypeMapperInterface\n{\n /** @var RootTypeMapperInterface */\n private $next;\n\n public function __construct(RootTypeMapperInterface $next)\n {\n $this->next = $next;\n }\n\n public function toGraphQLOutputType(Type $type, ?OutputType $subType, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?OutputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLOutputType($type, $subType, $refMethod, $docBlockObj);\n }\n\n public function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, ReflectionMethod $refMethod, DocBlock $docBlockObj): ?InputType\n {\n if ($type instanceof Scalar) {\n // AnyScalarType is a class implementing the Webonyx ScalarType type.\n return AnyScalarType::getInstance();\n }\n // If the PHPDoc type is not "Scalar", let\'s pass the control to the next type mapper in the chain\n return $this->next->toGraphQLInputType($type, $subType, $argumentName, $refMethod, $docBlockObj);\n }\n\n /**\n * Returns a GraphQL type by name.\n * If this root type mapper can return this type in "toGraphQLOutputType" or "toGraphQLInputType", it should\n * also map these types by name in the "mapNameToType" method.\n *\n * @param string $typeName The name of the GraphQL type\n * @return NamedType|null\n */\n public function mapNameToType(string $typeName): ?NamedType\n {\n if ($typeName === AnyScalarType::NAME) {\n return AnyScalarType::getInstance();\n }\n return null;\n }\n}\n')),(0,r.kt)("p",null,"Now, in order to create an instance of your ",(0,r.kt)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.kt)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class AnyScalarTypeMapperFactory implements RootTypeMapperFactoryInterface\n{\n public function create(RootTypeMapperInterface $next, RootTypeMapperFactoryContext $context): RootTypeMapperInterface\n {\n return new AnyScalarTypeMapper($next);\n }\n}\n")),(0,r.kt)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.kt)("p",null,"You can register your own root mapper factories using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, the factory will be automatically registered, you have nothing to do (the service\nis automatically tagged with the "graphql.root_type_mapper_factory" tag).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d49884c9.a42f768a.js b/assets/js/d49884c9.ab0ad481.js similarity index 99% rename from assets/js/d49884c9.a42f768a.js rename to assets/js/d49884c9.ab0ad481.js index 1f9e19d78c..0ca8c46e9c 100644 --- a/assets/js/d49884c9.a42f768a.js +++ b/assets/js/d49884c9.ab0ad481.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[254],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},8814:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/docs/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/next/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/queries.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/next/other-frameworks"},next:{title:"Mutations",permalink:"/docs/next/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[254],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),i=n(6550),s=n(1980),u=n(7392),p=n(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,p.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=u[n].value;a!==i&&(c(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;t=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;t=p[n]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function T(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},8814:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/docs/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/next/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/queries.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/next/other-frameworks"},next:{title:"Mutations",permalink:"/docs/next/mutations"}},p={},c=[{value:"Simple query",id:"simple-query",level:2},{value:"About annotations / attributes",id:"about-annotations--attributes",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.kt)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.kt)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.kt)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.kt)("p",null,"Read the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n #[Query]\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")))),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}m.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/d4c8693b.1dade46a.js b/assets/js/d4c8693b.f5b98357.js similarity index 98% rename from assets/js/d4c8693b.1dade46a.js rename to assets/js/d4c8693b.f5b98357.js index 98534cd402..a15b4bc1a2 100644 --- a/assets/js/d4c8693b.1dade46a.js +++ b/assets/js/d4c8693b.f5b98357.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1427],{3925:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},s=void 0,o={unversionedId:"internals",id:"version-4.1/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.1/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.1/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/internals.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},sidebar:"version-4.1/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.1/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.1/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1427],{3925:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>m});var p=t(7462),r=(t(7294),t(3905)),n=t(1839);const i={id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},s=void 0,o={unversionedId:"internals",id:"version-4.1/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-4.1/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/4.1/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/internals.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals",original_id:"internals"},sidebar:"version-4.1/docs",previous:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/4.1/troubleshooting"}},l={},m=[{value:"Mapping types",id:"mapping-types",level:2},{value:"Root type mappers",id:"root-type-mappers",level:2},{value:"Class type mappers",id:"class-type-mappers",level:2},{value:"Registering a type mapper in Symfony",id:"registering-a-type-mapper-in-symfony",level:3},{value:"Registering a type mapper using the SchemaFactory",id:"registering-a-type-mapper-using-the-schemafactory",level:3},{value:"Recursive type mappers",id:"recursive-type-mappers",level:2},{value:"Parameter mapper middlewares",id:"parameter-mapper-middlewares",level:2}],y={toc:m},u="wrapper";function d(e){let{components:a,...t}=e;return(0,r.kt)(u,(0,p.Z)({},y,t,{components:a,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"mapping-types"},"Mapping types"),(0,r.kt)("p",null,'The core of GraphQLite is its ability to map PHP types to GraphQL types. This mapping is performed by a series of\n"type mappers".'),(0,r.kt)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Parameter mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Root type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n subgraph RecursiveTypeMapperInterface\n BaseTypeMapper--\x3eRecursiveTypeMapper\n end\n subgraph TypeMapperInterface\n RecursiveTypeMapper--\x3eYourCustomTypeMapper\n YourCustomTypeMapper--\x3ePorpaginasTypeMapper\n PorpaginasTypeMapper--\x3eGlobTypeMapper\n end\n class YourCustomRootTypeMapper,YourCustomTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.kt)("p",null,"These type mappers are the first type mappers called."),(0,r.kt)("p",null,"They are responsible for:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.kt)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.kt)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.kt)("li",{parentName:"ul"},"mapping union types"),(0,r.kt)("li",{parentName:"ul"},"mapping enums")),(0,r.kt)("p",null,"Root type mappers have access to the ",(0,r.kt)("em",{parentName:"p"},"context"),' of a type: they can access the PHP DocBlock and read annotations.\nIf you want to write a custom type mapper that needs access to annotations, it needs to be a "root type mapper".'),(0,r.kt)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.kt)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.kt)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"FinalRootTypeMapper"),": the last type mapper of the chain, used to throw error if no other type mapper managed to handle the type.")),(0,r.kt)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.kt)(n.G,{chart:"graph TD;\n classDef custom fill:#cfc,stroke:#7a7,stroke-width:2px,stroke-dasharray: 5, 5;\n subgraph RootTypeMapperInterface\n NullableTypeMapperAdapter--\x3eCompoundTypeMapper\n CompoundTypeMapper--\x3eIteratorTypeMapper\n IteratorTypeMapper--\x3eYourCustomRootTypeMapper\n YourCustomRootTypeMapper--\x3eMyCLabsEnumTypeMapper\n MyCLabsEnumTypeMapper--\x3eBaseTypeMapper\n BaseTypeMapper--\x3eFinalRootTypeMapper\n end\n class YourCustomRootTypeMapper custom;",mdxType:"Mermaid"}),(0,r.kt)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.kt)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.kt)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.kt)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.kt)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.kt)("a",{parentName:"li",href:"/docs/4.1/pagination"},"special paginated type"),".")),(0,r.kt)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.kt)("p",null,'If you are using the GraphQLite Symfony bundle, you can register a type mapper by tagging the service with the "graphql.type_mapper" tag.'),(0,r.kt)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.kt)("p",null,"If you are using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.kt)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.kt)("p",null,"(Classes implementing the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.kt)("p",null,"There is only one implementation of the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.kt)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.kt)("p",null,'Standard "class type mappers" are mapping a given PHP class to a GraphQL type. But they do not handle class hierarchies.\nThis is the role of the "recursive type mapper".'),(0,r.kt)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.kt)("p",null,'Since "B" ',(0,r.kt)("em",{parentName:"p"},"is a"),' "A", the "recursive type mapper" role is to make sure that "B" will also map to GraphQL type "AType".'),(0,r.kt)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.kt)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.kt)("p",null,"Let's have a look at a simple query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",null,"As you may know, ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/query-plan"},"the ",(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to inject an argument in a method and if this argument is not a GraphQL input type or if you want to alter the way input types are imported (for instance if you want to add a validation step)"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d589d3a7.f4e2e0db.js b/assets/js/d589d3a7.4dbb3b64.js similarity index 94% rename from assets/js/d589d3a7.f4e2e0db.js rename to assets/js/d589d3a7.4dbb3b64.js index b6fa793ccf..1f4d676e8b 100644 --- a/assets/js/d589d3a7.f4e2e0db.js +++ b/assets/js/d589d3a7.4dbb3b64.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7162],{9998:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/docs/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/next/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/getting-started.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/next/"},next:{title:"Symfony bundle",permalink:"/docs/next/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,n.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,n.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/symfony-bundle"},"Get started with Symfony")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/laravel-package"},"Get started with Laravel")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7162],{9998:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/docs/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/next/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/getting-started.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/next/"},next:{title:"Symfony bundle",permalink:"/docs/next/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,n.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,n.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/symfony-bundle"},"Get started with Symfony")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/laravel-package"},"Get started with Laravel")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/docs/next/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d6188fd4.741060a1.js b/assets/js/d6188fd4.057acc4e.js similarity index 98% rename from assets/js/d6188fd4.741060a1.js rename to assets/js/d6188fd4.057acc4e.js index 04bfdb96f3..df71646f42 100644 --- a/assets/js/d6188fd4.741060a1.js +++ b/assets/js/d6188fd4.057acc4e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9999],{5997:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-6.1/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-6.1/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/implementing-security.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9999],{5997:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"version-6.1/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/versioned_docs/version-6.1/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/implementing-security.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d6b4b60c.4544dd32.js b/assets/js/d6b4b60c.dd968bd2.js similarity index 99% rename from assets/js/d6b4b60c.4544dd32.js rename to assets/js/d6b4b60c.dd968bd2.js index 33b015000e..41527c89d7 100644 --- a/assets/js/d6b4b60c.4544dd32.js +++ b/assets/js/d6b4b60c.dd968bd2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1327],{9842:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.0/annotations_reference",title:"Annotations reference",description:"@Query annotation",source:"@site/versioned_docs/version-4.0/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.0/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/annotations_reference.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.0/docs",previous:{title:"Migrating",permalink:"/docs/4.0/migrating"},next:{title:"Semantic versioning",permalink:"/docs/4.0/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here.')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here.')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"http://localhost:3000/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1327],{9842:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>p,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var n=a(7462),l=(a(7294),a(3905));a(1839);const r={id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.0/annotations_reference",title:"Annotations reference",description:"@Query annotation",source:"@site/versioned_docs/version-4.0/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.0/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/annotations_reference.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.0/docs",previous:{title:"Migrating",permalink:"/docs/4.0/migrating"},next:{title:"Semantic versioning",permalink:"/docs/4.0/semver"}},p={},d=[{value:"@Query annotation",id:"query-annotation",level:2},{value:"@Mutation annotation",id:"mutation-annotation",level:2},{value:"@Type annotation",id:"type-annotation",level:2},{value:"@ExtendType annotation",id:"extendtype-annotation",level:2},{value:"@Field annotation",id:"field-annotation",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"@Logged annotation",id:"logged-annotation",level:2},{value:"@Right annotation",id:"right-annotation",level:2},{value:"@FailWith annotation",id:"failwith-annotation",level:2},{value:"@HideIfUnauthorized annotation",id:"hideifunauthorized-annotation",level:2},{value:"@InjectUser annotation",id:"injectuser-annotation",level:2},{value:"@Security annotation",id:"security-annotation",level:2},{value:"@Factory annotation",id:"factory-annotation",level:2},{value:"@UseInputType annotation",id:"useinputtype-annotation",level:2},{value:"@Decorate annotation",id:"decorate-annotation",level:2},{value:"@Autowire annotation",id:"autowire-annotation",level:2},{value:"@HideParameter annotation",id:"hideparameter-annotation",level:2},{value:"@Validate annotation",id:"validate-annotation",level:2},{value:"@Assertion annotation",id:"assertion-annotation",level:2},{value:"@EnumType annotation",id:"enumtype-annotation",level:2}],m={toc:d},u="wrapper";function k(t){let{components:e,...a}=t;return(0,l.kt)(u,(0,n.Z)({},m,a,{components:e,mdxType:"MDXLayout"}),(0,l.kt)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The targeted class. If no class is passed, the type applies to the current class. The current class is assumed to be an entity. If the "class" attribute is passed, ',(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"the class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The name of the GraphQL type generated. If not passed, the name of the class is used. If the class ends with "Type", the "Type" suffix is removed')),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.kt)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"external"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"external type declaration"),' or not. You usually do not need to use this attribute since this value defaults to true if a "class" attribute is set. This is only useful if you are declaring a type with no PHP class mapping using the "name" attribute.')))),(0,l.kt)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"class"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/extend_type"},"The class annotated with ",(0,l.kt)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},"see below"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.kt)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.kt)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.kt)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here.')))),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.kt)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.kt)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"phpType"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no"),"(*)"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"annotations"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"array\\"),(0,l.kt)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "@Logged" or "@Right" annotation here.')))),(0,l.kt)("p",null,"(*) ",(0,l.kt)("strong",{parentName:"p"},"Note"),": ",(0,l.kt)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.kt)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("p",null,"This annotation allows no attributes."),(0,l.kt)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.kt)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation is used to declare a default value to return in the user is not authorized to see a specific\nquery / mutation / field (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"mixed"),(0,l.kt)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.kt)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query / mutation / field if the user is not authorized\nto access it (according to the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.kt)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.kt)("p",null,"Use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery / mutation / field."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.kt)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used to check fin-grained access rights.\nIt is very flexible: it allows you to pass an expression that can contains custom logic."),(0,l.kt)("p",null,"See ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"default")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.kt)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"default"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"bool"),(0,l.kt)("td",{parentName:"tr",align:null},"If ",(0,l.kt)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.kt)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.kt)("a",{parentName:"td",href:"http://localhost:3000/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.kt)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.kt)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"inputType")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.kt)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.kt)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.kt)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.kt)("p",null,"Useful to inject services directly into ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"identifier")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},'The identifier of the service to fetch. This is optional. Please avoid using this attribute as this leads to a "service locator" anti-pattern.')))),(0,l.kt)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.kt)("p",null,"Removes ",(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.kt)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.kt)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"rule")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.kt)("p",null,"Sample:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.kt)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.kt)("p",null,(0,l.kt)("a",{parentName:"p",href:"/docs/4.0/validation"},"Validates a user input"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.kt)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," third party package.\nIt is available out of the box if you use the Symfony bundle."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"for")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"yes")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"constraint")),(0,l.kt)("td",{parentName:"tr",align:null},"*yes"),(0,l.kt)("td",{parentName:"tr",align:null},"annotation"),(0,l.kt)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.kt)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"@EnumType"),' annotation is used to change the name of a "Enum" type.\nNote that if you do not want to change the name, the annotation is optionnal. Any object extending ',(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.kt)("p",null,(0,l.kt)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Attribute"),(0,l.kt)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.kt)("th",{parentName:"tr",align:null},"Type"),(0,l.kt)("th",{parentName:"tr",align:null},"Definition"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},"name"),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("em",{parentName:"td"},"no")),(0,l.kt)("td",{parentName:"tr",align:null},"string"),(0,l.kt)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d7067606.e545a270.js b/assets/js/d7067606.7c1d6410.js similarity index 99% rename from assets/js/d7067606.e545a270.js rename to assets/js/d7067606.7c1d6410.js index bd86f9cfe0..ba4deff484 100644 --- a/assets/js/d7067606.e545a270.js +++ b/assets/js/d7067606.7c1d6410.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1684],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),l=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,i]),tabValues:i}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,i.Z)("tabs__item",v.tabItem,l?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2660:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const i={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-6.1/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/laravel-package-advanced.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/internals"}},s={},u=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],p={toc:u},c="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(c,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n')),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1684],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),i=a(6010),l=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),i=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(n.location.search);t.set(i,e),n.replace({...n.location,search:t.toString()})}),[i,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:i}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,i]),tabValues:i}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,i.Z)("tabs__item",v.tabItem,l?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2660:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const i={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-6.1/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.1/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/laravel-package-advanced.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/internals"}},s={},u=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],p={toc:u},c="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(c,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n')),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n')),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d8037f4c.406c5fa5.js b/assets/js/d8037f4c.0fe7cd3c.js similarity index 97% rename from assets/js/d8037f4c.406c5fa5.js rename to assets/js/d8037f4c.0fe7cd3c.js index b2a92e82af..067867b31b 100644 --- a/assets/js/d8037f4c.406c5fa5.js +++ b/assets/js/d8037f4c.0fe7cd3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1692],{6486:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-6.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-6.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/6.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/troubleshooting.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.0/internals"},next:{title:"Migrating",permalink:"/docs/6.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1692],{6486:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(7462),r=(o(7294),o(3905));o(1839);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-6.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-6.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/6.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/troubleshooting.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.0/internals"},next:{title:"Migrating",permalink:"/docs/6.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.kt)(c,(0,n.Z)({},p,o,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.kt)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.kt)("p",null,"The message says that Symfony is trying to instantiate an input type as a service. This can happen if you put your\nGraphQLite controllers in the Symfony controller namespace (",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default). Symfony will assume that any\nobject type-hinted in a method of a controller is a service (",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/service_container/3.3-di-changes.html#controllers-are-registered-as-services"},'because all controllers are tagged with the "controller.service_arguments" tag'),")"),(0,r.kt)("p",null,"To fix this issue, do not put your GraphQLite controller in the same namespace as the Symfony controllers and\nreconfigure your ",(0,r.kt)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d8ff000f.f23621b2.js b/assets/js/d8ff000f.cffb1b5a.js similarity index 99% rename from assets/js/d8ff000f.f23621b2.js rename to assets/js/d8ff000f.cffb1b5a.js index a553d3f744..00d55f70b2 100644 --- a/assets/js/d8ff000f.f23621b2.js +++ b/assets/js/d8ff000f.cffb1b5a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8845],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},6912:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>b,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const s={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},l=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/docs/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/next/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/doctrine-annotations-attributes.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/next/migrating"},next:{title:"Annotations reference",permalink:"/docs/next/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],d={toc:p},h="wrapper";function b(t){let{components:e,...n}=t;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8845],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},6912:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>b,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const s={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},l=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/docs/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/next/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/doctrine-annotations-attributes.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/next/migrating"},next:{title:"Annotations reference",permalink:"/docs/next/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],d={toc:p},h="wrapper";function b(t){let{components:e,...n}=t;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d9523c62.4e46fc76.js b/assets/js/d9523c62.cbe8d3dd.js similarity index 98% rename from assets/js/d9523c62.4e46fc76.js rename to assets/js/d9523c62.cbe8d3dd.js index 180e337f6e..c8db966a0a 100644 --- a/assets/js/d9523c62.4e46fc76.js +++ b/assets/js/d9523c62.cbe8d3dd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1126],{8514:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},r=void 0,l={unversionedId:"external_type_declaration",id:"version-4.0/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.0/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/4.0/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/external_type_declaration.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-4.0/docs",previous:{title:"Extending a type",permalink:"/docs/4.0/extend_type"},next:{title:"Input types",permalink:"/docs/4.0/input-types"}},s={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,i.kt)("li",{parentName:"ul"},"etc.")),(0,i.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.kt)("p",null,"GraphQLite allows you to use a ",(0,i.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("p",null,"In methods with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,i.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.kt)("h2",{id:"sourcefield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.kt)("p",null,"If you don't want to rewrite all ",(0,i.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')),(0,i.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.kt)("h2",{id:"magicfield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,i.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')),(0,i.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,i.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.kt)("p",null,"Any annotations described in the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization"},"Authentication and authorization page")," can be used in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,i.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1126],{8514:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},r=void 0,l={unversionedId:"external_type_declaration",id:"version-4.0/external_type_declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an annotation on a domain class.",source:"@site/versioned_docs/version-4.0/external_type_declaration.mdx",sourceDirName:".",slug:"/external_type_declaration",permalink:"/docs/4.0/external_type_declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/external_type_declaration.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"external_type_declaration",title:"External type declaration",sidebar_label:"External type declaration",original_id:"external_type_declaration"},sidebar:"version-4.0/docs",previous:{title:"Extending a type",permalink:"/docs/4.0/extend_type"},next:{title:"Input types",permalink:"/docs/4.0/input-types"}},s={},p=[{value:"@Type annotation with the class attribute",id:"type-annotation-with-the-class-attribute",level:2},{value:"@SourceField annotation",id:"sourcefield-annotation",level:2},{value:"@MagicField annotation",id:"magicfield-annotation",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without annotations)",id:"declaring-fields-dynamically-without-annotations",level:2}],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.kt)("p",null,"For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.kt)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with annotations from the view layer"),(0,i.kt)("li",{parentName:"ul"},"etc.")),(0,i.kt)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.kt)("p",null,"GraphQLite allows you to use a ",(0,i.kt)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.kt)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType\n{\n /**\n * @Field()\n */\n public function getId(Product $product): string\n {\n return $product->getId();\n }\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.kt)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("p",null,"In methods with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,i.kt)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.kt)("h2",{id:"sourcefield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.kt)("p",null,"If you don't want to rewrite all ",(0,i.kt)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price")\n */\nclass ProductType\n{\n}\n')),(0,i.kt)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.kt)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.kt)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.kt)("h2",{id:"magicfield-annotation"},(0,i.kt)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,i.kt)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.kt)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse App\\Entities\\Product;\n\n/**\n * @Type()\n * @MagicField(name="name", outputType="String!")\n * @MagicField(name="price", outputType="Float")\n */\nclass ProductType\n{\n public function __get(string $property) {\n // return some magic property\n }\n}\n')),(0,i.kt)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.kt)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.kt)("p",null,"Please note that GraphQLite has no way to know the type of a magic property. Therefore, you have specify the GraphQL type\nof each property manually."),(0,i.kt)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.kt)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\nuse TheCodingMachine\\GraphQLite\\Annotations\\SourceField;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\nuse TheCodingMachine\\GraphQLite\\Annotations\\FailWith;\nuse App\\Entities\\Product;\n\n/**\n * @Type(class=Product::class)\n * @SourceField(name="name")\n * @SourceField(name="price", annotations={@Logged, @Right(name="CAN_ACCESS_Price", @FailWith(null)}))\n */\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.kt)("p",null,"Any annotations described in the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization"},"Authentication and authorization page")," can be used in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,i.kt)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.kt)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.kt)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.kt)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\FromSourceFieldsInterface;\n\n/**\n * @Type(class=Product::class)\n */\nclass ProductType implements FromSourceFieldsInterface\n{\n /**\n * Dynamically returns the array of source fields\n * to be fetched from the original object.\n *\n * @return SourceFieldInterface[]\n */\n public function getSourceFields(): array\n {\n // You may want to enable fields conditionally based on feature flags...\n if (ENABLE_STATUS_GLOBALLY) {\n return [\n new SourceField(['name'=>'status', 'logged'=>true]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/db6a6f31.6111f0aa.js b/assets/js/db6a6f31.c0058a7a.js similarity index 99% rename from assets/js/db6a6f31.6111f0aa.js rename to assets/js/db6a6f31.c0058a7a.js index 4423bb925e..05edaa66ca 100644 --- a/assets/js/db6a6f31.6111f0aa.js +++ b/assets/js/db6a6f31.c0058a7a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8369],{532:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},r=void 0,s={unversionedId:"fine-grained-security",id:"version-4.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/fine-grained-security.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},sidebar:"version-4.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.0/authentication_authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"}},l={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],u={toc:c},p="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(p,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"If the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"Using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.kt)("li",{parentName:"ul"},"...")),(0,i.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.kt)("code",null,"@Security")," annotation and Symfony's ",(0,i.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.kt)("h2",{id:"the-is_granted-function"},"The ",(0,i.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")),(0,i.kt)("p",null,"is similar to"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')),(0,i.kt)("p",null,"In addition, the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"In the example above, the ",(0,i.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,i.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#not-throwing-errors"},(0,i.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"You cannot use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')),(0,i.kt)("h2",{id:"available-scope"},"Available scope"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")),(0,i.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,i.kt)("p",null,"If you are using Symfony, you will ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.kt)("p",null,"If you are using Laravel, you will ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.kt)("p",null,"If you are using another framework, you need to know that the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8369],{532:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},r=void 0,s={unversionedId:"fine-grained-security",id:"version-4.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/fine-grained-security.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},sidebar:"version-4.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/4.0/authentication_authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"}},l={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],u={toc:c},p="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(p,(0,a.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"If the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"Using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.kt)("li",{parentName:"ul"},"...")),(0,i.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.kt)("code",null,"@Security")," annotation and Symfony's ",(0,i.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.kt)("h2",{id:"the-is_granted-function"},"The ",(0,i.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")),(0,i.kt)("p",null,"is similar to"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')),(0,i.kt)("p",null,"In addition, the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"In the example above, the ",(0,i.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,i.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#not-throwing-errors"},(0,i.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"You cannot use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')),(0,i.kt)("h2",{id:"available-scope"},"Available scope"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")),(0,i.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,i.kt)("p",null,"If you are using Symfony, you will ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.kt)("p",null,"If you are using Laravel, you will ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.kt)("p",null,"If you are using another framework, you need to know that the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.kt)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/dbf2bcb3.ba6e8806.js b/assets/js/dbf2bcb3.cae22b5f.js similarity index 98% rename from assets/js/dbf2bcb3.ba6e8806.js rename to assets/js/dbf2bcb3.cae22b5f.js index 12021cf0f9..58a082b060 100644 --- a/assets/js/dbf2bcb3.ba6e8806.js +++ b/assets/js/dbf2bcb3.cae22b5f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2523],{558:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-6.1/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-6.1/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/migrating.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2523],{558:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-6.1/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-6.1/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/migrating.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e126d786.195c05fa.js b/assets/js/e126d786.99a7c6b2.js similarity index 98% rename from assets/js/e126d786.195c05fa.js rename to assets/js/e126d786.99a7c6b2.js index f1b6dcc6f1..4396934941 100644 --- a/assets/js/e126d786.195c05fa.js +++ b/assets/js/e126d786.99a7c6b2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7971],{3277:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.2/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.2/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.2/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/migrating.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-4.2/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.2/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.2/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.2/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7971],{3277:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-4.2/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-4.2/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/4.2/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/migrating.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"version-4.2/docs",previous:{title:"Troubleshooting",permalink:"/docs/4.2/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/4.2/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/4.2/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e196b408.e6ac88af.js b/assets/js/e196b408.c5507d5e.js similarity index 98% rename from assets/js/e196b408.e6ac88af.js rename to assets/js/e196b408.c5507d5e.js index 884809b1a7..3c6bd001a2 100644 --- a/assets/js/e196b408.e6ac88af.js +++ b/assets/js/e196b408.c5507d5e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[242],{615:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/docs/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/next/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/implementing-security.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/next/fine-grained-security"},next:{title:"Operation complexity",permalink:"/docs/next/operation-complexity"}},c={},l=[],u={toc:l},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[242],{615:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var i=n(7462),r=(n(7294),n(3905));n(1839);const a={id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},o=void 0,s={unversionedId:"implementing-security",id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories.",source:"@site/docs/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/next/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/implementing-security.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"},sidebar:"docs",previous:{title:"Fine grained security",permalink:"/docs/next/fine-grained-security"},next:{title:"Operation complexity",permalink:"/docs/next/operation-complexity"}},c={},l=[],u={toc:l},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(p,(0,i.Z)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--info"},"At the time of writing, the Symfony Bundle and the Laravel package handle this implementation. For the latest documentation, please see their respective Github repositories."),(0,r.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,r.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged\n */\n public function isLogged(): bool;\n\n /**\n * Returns an object representing the current logged user.\n * Can return null if the user is not logged.\n */\n public function getUser(): ?object;\n}\n')),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right"\n *\n * @param mixed $subject The scope this right applies on. $subject is typically an object or a FQCN. Set $subject to "null" if the right is global.\n */\n public function isAllowed(string $right, $subject = null): bool;\n}\n')),(0,r.kt)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"using the ",(0,r.kt)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the @Right annotations).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e1b8bb84.a3131c7f.js b/assets/js/e1b8bb84.d98e7215.js similarity index 99% rename from assets/js/e1b8bb84.a3131c7f.js rename to assets/js/e1b8bb84.d98e7215.js index 9240aec73c..ea75c65496 100644 --- a/assets/js/e1b8bb84.a3131c7f.js +++ b/assets/js/e1b8bb84.d98e7215.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[66],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5800:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-5.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/5.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/laravel-package-advanced.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-5.0/docs",previous:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/5.0/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[66],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[d,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??d;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,i.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(d(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:c},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5800:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"version-5.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-5.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/5.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/laravel-package-advanced.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"version-5.0/docs",previous:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/5.0/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e29eb381.c2d22e4a.js b/assets/js/e29eb381.3bc795eb.js similarity index 99% rename from assets/js/e29eb381.c2d22e4a.js rename to assets/js/e29eb381.3bc795eb.js index ca05d340b9..7b94a18bcc 100644 --- a/assets/js/e29eb381.c2d22e4a.js +++ b/assets/js/e29eb381.3bc795eb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5593],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var a=t(7462),r=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),p=t(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function d(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function h(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(a.location.search);n.set(o,e),a.replace({...a.location,search:n.toString()})}),[o,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:a}),[c,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,o]=(0,p.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:a}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,o]),tabValues:o}}var y=t(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==l&&(c(n),s(a))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;n=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;n=p[t]??p[p.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function k(e){let{lazy:n,children:t,selectedValue:a}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function w(e){const n=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,n)),r.createElement(k,(0,a.Z)({},e,n)))}function v(e){const n=(0,y.Z)();return r.createElement(w,(0,a.Z)({key:String(n)},e))}},9508:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var a=t(7462),r=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},s=void 0,u={unversionedId:"other-frameworks",id:"version-4.1/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.1/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.1/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/other_frameworks.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.1/docs",previous:{title:"Universal service providers",permalink:"/docs/4.1/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.1/queries"}},p={},c=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:c},h="wrapper";function m(e){let{components:n,...l}=e;return(0,r.kt)(h,(0,a.Z)({},d,l,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If you are using ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony bundle"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"composer.json")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"index.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,r.kt)("p",null,(0,r.kt)("img",{src:t(1410).Z,width:"1132",height:"352"})))}m.isMDXComponent=!0},1410:(e,n,t)=>{t.d(n,{Z:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5593],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>v});var a=t(7462),r=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),p=t(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function d(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function h(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(a.location.search);n.set(o,e),a.replace({...a.location,search:n.toString()})}),[o,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:a}),[c,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,o]=(0,p.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:a}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,o]),tabValues:o}}var y=t(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==l&&(c(n),s(a))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;n=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;n=p[t]??p[p.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function k(e){let{lazy:n,children:t,selectedValue:a}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function w(e){const n=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(b,(0,a.Z)({},e,n)),r.createElement(k,(0,a.Z)({},e,n)))}function v(e){const n=(0,y.Z)();return r.createElement(w,(0,a.Z)({key:String(n)},e))}},9508:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var a=t(7462),r=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},s=void 0,u={unversionedId:"other-frameworks",id:"version-4.1/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.1/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.1/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/other_frameworks.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.1/docs",previous:{title:"Universal service providers",permalink:"/docs/4.1/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.1/queries"}},p={},c=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],d={toc:c},h="wrapper";function m(e){let{components:n,...l}=e;return(0,r.kt)(h,(0,a.Z)({},d,l,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If you are using ",(0,r.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,r.kt)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony bundle"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,r.kt)("h2",{id:"requirements"},"Requirements"),(0,r.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,r.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,r.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,r.kt)("p",null,"GraphQLite relies on the ",(0,r.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we also provide a ",(0,r.kt)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,r.kt)("h2",{id:"integration"},"Integration"),(0,r.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,r.kt)("p",null,"You can now use this schema with ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,r.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add a custom type mapper using a factory to create it.\n// Type mapper factories are useful if you need to inject the "recursive type mapper" into your type mapper constructor.\n$factory->addTypeMapperFactory($typeMapperFactory);\n// Add a root type mapper.\n$factory->addRootTypeMapper($rootTypeMapper);\n// Add a parameter mapper.\n$factory->addParameterMapper($parameterMapper);\n// Add a query provider. These are used to find queries and mutations in the application.\n$factory->addQueryProvider($queryProvider);\n// Add a query provider using a factory to create it.\n// Query provider factories are useful if you need to inject the "fields builder" into your query provider constructor.\n$factory->addQueryProviderFactory($queryProviderFactory);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n// Configures the time-to-live for the GraphQLite cache. Defaults to 2 seconds in dev mode.\n$factory->setGlobTtl(2);\n// Enables prod-mode (cache settings optimized for best performance).\n// This is a shortcut for `$schemaFactory->setGlobTtl(null)`\n$factory->prodMode();\n// Enables dev-mode (this is the default mode: cache settings optimized for best developer experience).\n// This is a shortcut for `$schemaFactory->setGlobTtl(2)`\n$factory->devMode();\n')),(0,r.kt)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,r.kt)("p",null,'Webonyx allows you pass a "context" object when running a query.\nFor some GraphQLite features to work (namely: the prefetch feature), GraphQLite needs you to initialize the Webonyx context\nwith an instance of the ',(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,r.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,r.kt)("p",null,"The smallest working example using no framework is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,r.kt)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,r.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,r.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,r.kt)("p",null,"If the framework you are using is compatible with PSR-15 (like Slim PHP or Zend-Expressive / Laminas), GraphQLite\ncomes with a PSR-15 middleware out of the box."),(0,r.kt)("p",null,"In order to get an instance of this middleware, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"// $schema is an instance of the GraphQL schema returned by SchemaFactory::createSchema (see previous chapter)\n$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$middleware = $builder->createMiddleware();\n\n// You can now inject your middleware in your favorite PSR-15 compatible framework.\n// For instance:\n$zendMiddlewarePipe->pipe($middleware);\n")),(0,r.kt)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'$builder->setUrl("/graphql"); // Modify the URL endpoint (defaults to /graphql)\n$config = $builder->getConfig(); // Returns a Webonyx ServerConfig object. Use this object to configure Webonyx in details.\n$builder->setConfig($config);\n\n$builder->setResponseFactory(new ResponseFactory()); // Set a PSR-18 ResponseFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setStreamFactory(new StreamFactory()); // Set a PSR-18 StreamFactory (not needed if you are using zend-framework/zend-diactoros ^2\n$builder->setHttpCodeDecider(new HttpCodeDecider()); // Set a class in charge of deciding the HTTP status code based on the response.\n')),(0,r.kt)("h3",{id:"example"},"Example"),(0,r.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,r.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"composer.json")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^4",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"index.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,r.kt)("p",null,"Here we are initializing a Zend ",(0,r.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,r.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,r.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n $builder = new Psr15GraphQLMiddlewareBuilder($container->get(Schema::class));\n return $builder->createMiddleware();\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,r.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,r.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"config/container.php")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,r.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,r.kt)("p",null,(0,r.kt)("img",{src:t(1410).Z,width:"1132",height:"352"})))}m.isMDXComponent=!0},1410:(e,n,t)=>{t.d(n,{Z:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/e2e51976.420e29b9.js b/assets/js/e2e51976.19f28336.js similarity index 99% rename from assets/js/e2e51976.420e29b9.js rename to assets/js/e2e51976.19f28336.js index d6adfc6bef..52cd93416b 100644 --- a/assets/js/e2e51976.420e29b9.js +++ b/assets/js/e2e51976.19f28336.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3019],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},3603:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>b,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const s={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},l=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-6.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-6.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/6.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/doctrine-annotations-attributes.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/6.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/6.0/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],d={toc:p},h="wrapper";function b(t){let{components:e,...n}=t;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}b.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3019],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},3603:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>b,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),o=(n(1839),n(4866)),i=n(5162);const s={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},l=void 0,u={unversionedId:"doctrine-annotations-attributes",id:"version-6.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-6.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/6.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/doctrine-annotations-attributes.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/6.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/6.0/annotations-reference"}},c={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],d={toc:p},h="wrapper";function b(t){let{components:e,...n}=t;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}b.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e347e63a.6ded22d4.js b/assets/js/e347e63a.68690188.js similarity index 98% rename from assets/js/e347e63a.6ded22d4.js rename to assets/js/e347e63a.68690188.js index 94f408df14..7b34d31037 100644 --- a/assets/js/e347e63a.6ded22d4.js +++ b/assets/js/e347e63a.68690188.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8932],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6662:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-6.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-6.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/6.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/prefetch-method.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/6.0/query-plan"},next:{title:"File uploads",permalink:"/docs/6.0/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8932],{5162:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),r=n(6010);const s={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:n,className:l}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(s.tabItem,l),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),r=n(7294),s=n(6010),l=n(2466),o=n(6550),i=n(1980),u=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function h(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),s=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(s),(0,r.useCallback)((e=>{if(!s)return;const t=new URLSearchParams(a.location.search);t.set(s,e),a.replace({...a.location,search:t.toString()})}),[s,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,s=h(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:s}))),[i,u]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,s]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),b=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:s}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),f(e)}),[u,f,s]),tabValues:s}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,l.o5)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(p(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,s.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:h},l,{className:(0,s.Z)("tabs__item",y.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;const s=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=s.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},s.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,s.Z)("tabs-container",y.tabList)},r.createElement(g,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function T(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},6662:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),s=(n(1839),n(4866)),l=n(5162);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-6.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-6.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/6.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/prefetch-method.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/6.0/query-plan"},next:{title:"File uploads",permalink:"/docs/6.0/file-uploads"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"The "prefetch" method",id:"the-prefetch-method",level:2},{value:"Input arguments",id:"input-arguments",level:2}],h={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.kt)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.kt)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem.\nAssuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "posts" and "users".\nThis method is described in the ',(0,r.kt)("a",{parentName:"p",href:"/docs/6.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.kt)("p",null,"But this can be difficult to implement. This is also only useful for relational databases. If your data comes from a\nNoSQL database or from the cache, this will not help."),(0,r.kt)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.kt)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedUsers\n * @return User\n */\n #[Field(prefetchMethod: "prefetchUsers")]\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchUsers")\n * @param mixed $prefetchedUsers\n * @return User\n */\n public function getUser($prefetchedUsers): User\n {\n // This method will receive the $prefetchedUsers as second argument. This is the return value of the "prefetchUsers" method below.\n // Using this prefetched list, it should be easy to map it to the post\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchUsers(iterable $posts)\n {\n // This function is called only once per GraphQL request\n // with the list of posts. You can fetch the list of users\n // associated with this posts in a single request,\n // for instance using a "IN" query in SQL or a multi-fetch\n // in your cache back-end.\n }\n}\n')))),(0,r.kt)("p",null,'When the "prefetchMethod" attribute is detected in the "@Field" annotation, the method is called automatically.\nThe first argument of the method is an array of instances of the main type.\nThe "prefetchMethod" can return absolutely anything (mixed). The return value will be passed as the second parameter of the "@Field" annotated method.'),(0,r.kt)("h2",{id:"input-arguments"},"Input arguments"),(0,r.kt)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.kt)("p",null,"For instance:"),(0,r.kt)(s.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass PostType {\n /**\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n #[Field(prefetchMethod: "prefetchComments")]\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type\n */\nclass PostType {\n /**\n * @Field(prefetchMethod="prefetchComments")\n * @param mixed $prefetchedComments\n * @return Comment[]\n */\n public function getComments($prefetchedComments): array\n {\n // ...\n }\n\n /**\n * @param Post[] $posts\n * @return mixed\n */\n public function prefetchComments(iterable $posts, bool $hideSpam, int $filterByScore)\n {\n // Parameters passed after the first parameter (hideSpam, filterByScore...) are automatically exposed\n // as GraphQL arguments for the "comments" field.\n }\n}\n')))),(0,r.kt)("p",null,"The prefetch method MUST be in the same class as the @Field-annotated method and MUST be public."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e45c611c.d5d420c8.js b/assets/js/e45c611c.13fab258.js similarity index 99% rename from assets/js/e45c611c.d5d420c8.js rename to assets/js/e45c611c.13fab258.js index 2094bd590a..aaf33863d7 100644 --- a/assets/js/e45c611c.d5d420c8.js +++ b/assets/js/e45c611c.13fab258.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4466],{3311:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-4.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-4.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/laravel-package-advanced.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.0/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.0/internals"}},p={},s=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],d={toc:s},u="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your input types."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,i.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("p",null,"You can use any validation rule described in ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.kt)("p",null,"In your query, if you explicitly return an object that extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class, the query result will be wrapped in a\n"paginator" type.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,i.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (`Illuminate\\Pagination\\LengthAwarePaginator`) and not on the interface (`Illuminate\\Contracts\\Pagination\\LengthAwarePaginator`). The interface itself is not iterable (it does not extend `Traversable`) and therefore, GraphQLite will refuse to iterate over it."),(0,i.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.kt)("p",null,"Note: if you are using ",(0,i.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")),(0,i.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,i.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,i.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id" outputType="ID!")\n * @MagicField(name="name" phpType="string")\n * @MagicField(name="categories" phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')),(0,i.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,i.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,i.kt)("p",null,"It would be tempting to put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,i.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.kt)("p",null,"In short:"),(0,i.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,i.kt)("div",{class:"alert alert--success"},"This works:",(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'```php\n/**\n* @MagicField(name="phone", phpType="App\\\\Phone")\n*/\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4466],{3311:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-4.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel.",source:"@site/versioned_docs/version-4.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/4.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/laravel-package-advanced.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.0/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.0/internals"}},p={},s=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],d={toc:s},u="wrapper";function h(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your input types."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,i.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,i.kt)("p",null,"You can use any validation rule described in ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.kt)("p",null,"In your query, if you explicitly return an object that extends ",(0,i.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class, the query result will be wrapped in a\n"paginator" type.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")),(0,i.kt)("p",null,"Notice that:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.kt)("li",{parentName:"ul"},"you MUST add a ",(0,i.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,i.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (`Illuminate\\Pagination\\LengthAwarePaginator`) and not on the interface (`Illuminate\\Contracts\\Pagination\\LengthAwarePaginator`). The interface itself is not iterable (it does not extend `Traversable`) and therefore, GraphQLite will refuse to iterate over it."),(0,i.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.kt)("p",null,"Note: if you are using ",(0,i.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")),(0,i.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,i.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,i.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id" outputType="ID!")\n * @MagicField(name="name" phpType="string")\n * @MagicField(name="categories" phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')),(0,i.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,i.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,i.kt)("p",null,"It would be tempting to put a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,i.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.kt)("p",null,"In short:"),(0,i.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"```php\nclass User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n```\n"))),(0,i.kt)("div",{class:"alert alert--success"},"This works:",(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},'```php\n/**\n* @MagicField(name="phone", phpType="App\\\\Phone")\n*/\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n```\n'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e4c5fdc3.2dfa0c08.js b/assets/js/e4c5fdc3.a81b7d1a.js similarity index 97% rename from assets/js/e4c5fdc3.2dfa0c08.js rename to assets/js/e4c5fdc3.a81b7d1a.js index 49c3df3304..b9c74db703 100644 --- a/assets/js/e4c5fdc3.2dfa0c08.js +++ b/assets/js/e4c5fdc3.a81b7d1a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2447],{6174:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-6.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-6.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/6.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/semver.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/6.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/6.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2447],{6174:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));a(1839);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-6.0/semver",title:"Our backward compatibility promise",description:"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as Semantic Versioning. In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example).",source:"@site/versioned_docs/version-6.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/6.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/semver.md",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/6.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/6.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("p",null,"Ensuring smooth upgrades of your project is a priority. That's why we promise you backward compatibility (BC) for all minor GraphQLite releases. You probably recognize this strategy as ",(0,n.kt)("a",{parentName:"p",href:"https://semver.org/"},"Semantic Versioning"),". In short, Semantic Versioning means that only major releases (such as 4.0, 5.0 etc.) are allowed to break backward compatibility. Minor releases (such as 4.0, 4.1 etc.) may introduce new features, but must do so without breaking the existing API of that release branch (4.x in the previous example)."),(0,n.kt)("p",null,'But sometimes, a new feature is not quite "dry" and we need a bit of time to find the perfect API.\nIn such cases, we prefer to gather feedback from real-world usage, adapt the API, or remove it altogether.\nDoing so is not possible with a no BC-break approach.'),(0,n.kt)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.kt)("strong",{parentName:"p"},"unstable")," or ",(0,n.kt)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.kt)("p",null,(0,n.kt)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.kt)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.kt)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.kt)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.kt)("p",null,"As a rule of thumb:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.kt)("li",{parentName:"ul"},"If you are extending GraphQLite features (if you are developing custom annotations, or if you are developing a GraphQlite integration\nwith a framework...), be sure to check the tags.")),(0,n.kt)("p",null,"Said otherwise:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.kt)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.kt)("pre",{parentName:"li"},(0,n.kt)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.kt)("p",null,"Finally, classes / methods annotated with the ",(0,n.kt)("inlineCode",{parentName:"p"},"@internal")," annotation are not meant to be used in your code or third-party library. They are meant for GraphQLite internal usage and they may break anytime. Do not use those directly."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e5d0e3cb.ab31c48d.js b/assets/js/e5d0e3cb.9aa24194.js similarity index 98% rename from assets/js/e5d0e3cb.ab31c48d.js rename to assets/js/e5d0e3cb.9aa24194.js index 94b90ff0b0..2df2160b4f 100644 --- a/assets/js/e5d0e3cb.ab31c48d.js +++ b/assets/js/e5d0e3cb.9aa24194.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4243],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8600:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.1/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.1/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.1/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/query_plan.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.1/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.1/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.1/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4243],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(7462),r=n(7294),l=n(6010),o=n(2466),u=n(6550),s=n(1980),i=n(7392),c=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,i.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=d(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[s,i]=m({queryString:n,groupId:a}),[p,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),b=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var b=n(2389);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=i[n].value;a!==u&&(p(t),s(a))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,l.Z)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":u===t})}),n??t)})))}function g(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",y.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(g,(0,a.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,a.Z)({key:String(t)},e))}},8600:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(7462),r=(n(7294),n(3905)),l=(n(1839),n(4866)),o=n(5162);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},s=void 0,i={unversionedId:"query-plan",id:"version-4.1/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-4.1/query_plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/4.1/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/query_plan.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.1/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.1/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.1/prefetch-method"}},c={},p=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],d={toc:p},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"the-problem"},"The problem"),(0,r.kt)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.kt)("p",null,"Let's have a look at the following query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.kt)("p",null,"A naive implementation will do this:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.kt)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.kt)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.kt)("p",null,'There are several ways to fix this problem. Assuming you are using a relational database, one solution is to try to look\nahead and perform only one query with a JOIN between "products" and "manufacturers".'),(0,r.kt)("p",null,'But how do I know if I should make the JOIN between "products" and "manufacturers" or not? I need to know ahead\nof time.'),(0,r.kt)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.kt)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use GraphQL\\Type\\Definition\\ResolveInfo;\n\nclass ProductsController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(ResolveInfo $info): array\n {\n if (isset($info->getFieldSelection()['manufacturer']) {\n // Let's perform a request with a JOIN on manufacturer\n } else {\n // Let's perform a request without a JOIN on manufacturer\n }\n // ...\n }\n}\n")))),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," is a class provided by Webonyx/GraphQL-PHP (the low-level GraphQL library used by GraphQLite).\nIt contains info about the query and what fields are requested. Using ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo::getFieldSelection"),' you can analyze the query\nand decide whether you should perform additional "JOINS" in your query or not.'),(0,r.kt)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.kt)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.kt)("a",{href:"https://github.com/webonyx/graphql-php/pull/436"},'next version of Webonyx/GraphQL-PHP will add a "query plan"'),"that allows a deeper analysis of the query."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e5d7b215.3c0d792a.js b/assets/js/e5d7b215.f6b6ec90.js similarity index 97% rename from assets/js/e5d7b215.3c0d792a.js rename to assets/js/e5d7b215.f6b6ec90.js index 2b82c30f0e..e5289729b3 100644 --- a/assets/js/e5d7b215.3c0d792a.js +++ b/assets/js/e5d7b215.f6b6ec90.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[153],{8869:(e,r,t)=>{t.r(r),t.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var i=t(7462),n=(t(7294),t(3905));t(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/docs/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/next/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/universal-service-providers.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/next/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/next/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...t}=e;return(0,n.kt)(d,(0,i.Z)({},c,t,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[153],{8869:(e,r,t)=>{t.r(r),t.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var i=t(7462),n=(t(7294),t(3905));t(1839);const a={id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},o=void 0,s={unversionedId:"universal-service-providers",id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",description:"container-interop/service-provider is an experimental project",source:"@site/docs/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/next/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/universal-service-providers.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"universal-service-providers",title:"Getting started with a framework compatible with container-interop/service-provider",sidebar_label:"Universal service providers"},sidebar:"docs",previous:{title:"Laravel package",permalink:"/docs/next/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/next/other-frameworks"}},p={},l=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Sample usage",id:"sample-usage",level:2}],c={toc:l},d="wrapper";function h(e){let{components:r,...t}=e;return(0,n.kt)(d,(0,i.Z)({},c,t,{components:r,mdxType:"MDXLayout"}),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider")," is an experimental project\naiming to bring interoperability between framework module systems."),(0,n.kt)("p",null,"If your framework is compatible with ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/container-interop/service-provider/"},"container-interop/service-provider"),",\nGraphQLite comes with a service provider that you can leverage."),(0,n.kt)("h2",{id:"installation"},"Installation"),(0,n.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.kt)("h2",{id:"requirements"},"Requirements"),(0,n.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.kt)("p",null,"GraphQLite relies on the ",(0,n.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and we provide a ",(0,n.kt)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,n.kt)("h2",{id:"integration"},"Integration"),(0,n.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,n.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. The service provider provides this ",(0,n.kt)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.kt)("h2",{id:"sample-usage"},"Sample usage"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-json",metastring:'title="composer.json"',title:'"composer.json"'},'{\n "require": {\n "mnapoli/simplex": "^0.5",\n "thecodingmachine/graphqlite-universal-service-provider": "^3",\n "thecodingmachine/symfony-cache-universal-module": "^1"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="index.php"',title:'"index.php"'},"set('graphqlite.namespace.types', ['App\\\\Types']);\n$container->set('graphqlite.namespace.controllers', ['App\\\\Controllers']);\n\n$schema = $container->get(Schema::class);\n\n// or if you want the PSR-15 middleware:\n\n$middleware = $container->get(Psr15GraphQLMiddlewareBuilder::class);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e617c97b.902973d6.js b/assets/js/e617c97b.198da7fd.js similarity index 98% rename from assets/js/e617c97b.902973d6.js rename to assets/js/e617c97b.198da7fd.js index 29109d882a..a368997636 100644 --- a/assets/js/e617c97b.902973d6.js +++ b/assets/js/e617c97b.198da7fd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3668],{6108:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},l=void 0,o={unversionedId:"changelog",id:"version-4.1/changelog",title:"Changelog",description:"4.1",source:"@site/versioned_docs/version-4.1/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.1/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/CHANGELOG.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},sidebar:"version-4.1/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},s={},p=[{value:"4.1",id:"41",level:2},{value:"4.0",id:"40",level:2}],d={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"41"},"4.1"),(0,i.kt)("p",null,"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("p",null,"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("p",null,"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"40"},"4.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/error-handling"},"GraphQL errors")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.kt)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can map ",(0,i.kt)("a",{parentName:"li",href:"input-types#declaring-several-input-types-for-the-same-php-class"},"a given PHP class to several PHP input types")," (a PHP class can have several ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/extend_input_type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("p",null,"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("p",null,"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("p",null,"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3668],{6108:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(7462),i=(a(7294),a(3905));a(1839);const r={id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},l=void 0,o={unversionedId:"changelog",id:"version-4.1/changelog",title:"Changelog",description:"4.1",source:"@site/versioned_docs/version-4.1/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/4.1/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/CHANGELOG.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog",original_id:"changelog"},sidebar:"version-4.1/docs",previous:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},s={},p=[{value:"4.1",id:"41",level:2},{value:"4.0",id:"40",level:2}],d={toc:p},u="wrapper";function c(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"41"},"4.1"),(0,i.kt)("p",null,"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("p",null,"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("p",null,"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"40"},"4.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("p",null,"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/error-handling"},"GraphQL errors")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.kt)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can map ",(0,i.kt)("a",{parentName:"li",href:"input-types#declaring-several-input-types-for-the-same-php-class"},"a given PHP class to several PHP input types")," (a PHP class can have several ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/extend_input_type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("p",null,"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("p",null,"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/4.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("p",null,"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e63ebe23.1bae7062.js b/assets/js/e63ebe23.d16cff09.js similarity index 99% rename from assets/js/e63ebe23.1bae7062.js rename to assets/js/e63ebe23.d16cff09.js index e3fd56d841..98e33e899a 100644 --- a/assets/js/e63ebe23.1bae7062.js +++ b/assets/js/e63ebe23.d16cff09.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4688],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},4636:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-6.0/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-6.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/6.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/input-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/6.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"}},s={},c=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.kt)("a",{parentName:"p",href:"input-attribute"},(0,l.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,l.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.kt)("p",null,"Using the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var string|null\n */\n private ?string $name = null;\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call the ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,l.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,l.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.kt)("p",null,"Simple usage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,l.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.kt)("p",null,"You can add multiple ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /** @var int|null */\n protected $age;\n\n /**\n * @Field()\n * @param int|null $age\n */\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n')))),(0,l.kt)("p",null,"There are 2 input types added to the ",(0,l.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4688],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const r={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(r.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>I});var a=n(7462),l=n(7294),r=n(6010),i=n(2466),o=n(6550),u=n(1980),p=n(7392),s=n(12);function c(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),r=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(r),(0,l.useCallback)((e=>{if(!r)return;const t=new URLSearchParams(a.location.search);t.set(r,e),a.replace({...a.location,search:t.toString()})}),[r,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[i,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[u,p]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),f=(()=>{const e=u??c;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),y(e)}),[p,y,r]),tabValues:r}}var f=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:d},i,{className:(0,r.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function k(e){let{lazy:t,children:n,selectedValue:a}=e;const r=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=r.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},r.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return l.createElement("div",{className:(0,r.Z)("tabs-container",b.tabList)},l.createElement(g,(0,a.Z)({},e,t)),l.createElement(k,(0,a.Z)({},e,t)))}function I(e){const t=(0,f.Z)();return l.createElement(v,(0,a.Z)({key:String(t)},e))}},4636:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(7462),l=(n(7294),n(3905)),r=(n(1839),n(4866)),i=n(5162);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-6.0/input-types",title:"Input types",description:"Let's assume you are developing an API that returns a list of cities around a location.",source:"@site/versioned_docs/version-6.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/6.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/input-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/6.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"}},s={},c=[{value:"#[Input] Attribute",id:"input-attribute",level:2},{value:"Multiple Input Types from the same class",id:"multiple-input-types-from-the-same-class",level:3},{value:"Factory",id:"factory",level:2},{value:"Specifying the input type name",id:"specifying-the-input-type-name",level:3},{value:"Forcing an input type",id:"forcing-an-input-type",level:3},{value:"Declaring several input types for the same PHP class",id:"declaring-several-input-types-for-the-same-php-class",level:3},{value:"Ignoring some parameters",id:"ignoring-some-parameters",level:3}],d={toc:c},m="wrapper";function h(e){let{components:t,...n}=e;return(0,l.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.kt)("p",null,"Your GraphQL query might look like this:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return City[]\n */\n #[Query]\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return City[]\n */\n public function getCities(Location $location, float $radius): array\n {\n // Some code that returns an array of cities.\n }\n}\n\n// Class Location is a simple value-object.\nclass Location\n{\n private $latitude;\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"If you try to run this code, you will get the following error:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.kt)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.kt)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.kt)("strong",{parentName:"p"},"Input Type"),"."),(0,l.kt)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.kt)("a",{parentName:"p",href:"input-attribute"},(0,l.kt)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.kt)("a",{parentName:"p",href:"factory"},"Factory method"),"."),(0,l.kt)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.kt)("p",null,"Using the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.kt)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input]\nclass Location\n{\n\n #[Field]\n private ?string $name = null;\n\n #[Field]\n private float $latitude;\n\n #[Field]\n private float $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Input\n */\nclass Location\n{\n\n /**\n * @Field\n * @var string|null\n */\n private ?string $name = null;\n\n /**\n * @Field\n * @var float\n */\n private $latitude;\n\n /**\n * @Field\n * @var float\n */\n private $longitude;\n\n public function __construct(float $latitude, float $longitude)\n {\n $this->latitude = $latitude;\n $this->longitude = $longitude;\n }\n\n public function setName(string $name): void\n {\n $this->name = $name;\n }\n\n public function getLatitude(): float\n {\n return $this->latitude;\n }\n\n public function getLongitude(): float\n {\n return $this->longitude;\n }\n}\n")))),(0,l.kt)("p",null,"Now if you call the ",(0,l.kt)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.kt)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.kt)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.kt)("p",null,"There are some important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.kt)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.kt)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.kt)("li",{parentName:"ul"},"For private or protected properties implemented, a public setter is required (if they are not set via the constructor). For example ",(0,l.kt)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.kt)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.kt)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.kt)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.kt)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.kt)("li",{parentName:"ul"},"It's advised to use the ",(0,l.kt)("inlineCode",{parentName:"li"},"#[Input]")," attribute on DTO style input type objects and not directly on your model objects. Using it on your model objects can cause coupling in undesirable ways.")),(0,l.kt)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.kt)("p",null,"Simple usage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input"),' annotation on a class creates a GraphQL input named by class name + "Input" suffix if a class name does not end with it already. Ex. ',(0,l.kt)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.kt)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.kt)("p",null,"You can add multiple ",(0,l.kt)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Input(name: 'CreateUserInput', default: true)]\n#[Input(name: 'UpdateUserInput', update: true)]\nclass UserInput\n{\n\n #[Field]\n public string $username;\n\n #[Field(for: 'CreateUserInput')]\n public string $email;\n\n #[Field(for: 'CreateUserInput', inputType: 'String!')]\n #[Field(for: 'UpdateUserInput', inputType: 'String')]\n public string $password;\n\n protected ?int $age;\n\n\n #[Field]\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Input(name="CreateUserInput", default=true)\n * @Input(name="UpdateUserInput", update=true)\n */\nclass UserInput\n{\n\n /**\n * @Field()\n * @var string\n */\n public $username;\n\n /**\n * @Field(for="CreateUserInput")\n * @var string\n */\n public string $email;\n\n /**\n * @Field(for="CreateUserInput", inputType="String!")\n * @Field(for="UpdateUserInput", inputType="String")\n * @var string|null\n */\n public $password;\n\n /** @var int|null */\n protected $age;\n\n /**\n * @Field()\n * @param int|null $age\n */\n public function setAge(?int $age): void\n {\n $this->age = $age;\n }\n}\n')))),(0,l.kt)("p",null,"There are 2 input types added to the ",(0,l.kt)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.kt)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.kt)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.kt)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.kt)("li",{parentName:"ul"},"Field ",(0,l.kt)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.kt)("p",null,"Note that ",(0,l.kt)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput"),". It should be used when input type is used for a partial update,\nIt makes all fields optional and removes all default values from thus prevents setting default values via setters or directly to public properties.\nIn example above if you use the class as ",(0,l.kt)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.kt)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.kt)("inlineCode",{parentName:"p"},"null"),", while in PHP 8 they will be in not initialized state - this can be used as a trick\nto check if user actually passed a value for a certain field."),(0,l.kt)("h2",{id:"factory"},"Factory"),(0,l.kt)("p",null,"A ",(0,l.kt)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.kt)("p",null,"Here is an example of factory:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n */\n #[Factory]\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory annotation will create automatically a LocationInput input type in GraphQL.\n *\n * @Factory()\n */\n public function createLocation(float $latitude, float $longitude): Location\n {\n return new Location($latitude, $longitude);\n }\n}\n")))),(0,l.kt)("p",null,"and now, you can run query like this:"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-graphql"},"query {\n getCities(location: {\n latitude: 45.0,\n longitude: 0.0,\n },\n radius: 42)\n {\n id,\n name\n }\n}\n")),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.kt)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.kt)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.kt)("p",null,"A few important things to notice:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"The container MUST contain the factory class. The identifier of the factory MUST be the fully qualified class name of the class that contains the factory.\nThis is usually already the case if you are using a container with auto-wiring capabilities"),(0,l.kt)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.kt)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.kt)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.kt)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Factory()\n */\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,l.kt)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.kt)("p",null,'Note that you need to add the "default" attribute is you want your factory to be used by default (more on this in\nthe next chapter).'),(0,l.kt)("p",null,"Unless you want to have several factories for the same PHP class, the input type name will be completely transparent\nto you, so there is no real reason to customize it."),(0,l.kt)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.kt)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'#[Factory]\n#[UseInputType(for: "$id", inputType:"ID!")]\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @UseInputType(for="$id", inputType="ID!")\n */\npublic function getProductById(string $id): Product\n{\n return $this->productRepository->findById($id);\n}\n')))),(0,l.kt)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.kt)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,l.kt)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.kt)("p",null,"Here is an annotated sample:"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n */\n #[Factory(name: "ProductRefInput", default: true)]\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n */\n #[Factory(name: "CreateProductInput", default: false)]\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n */\n #[Mutation]\n #[UseInputType(for: "$product", inputType: "CreateProductInput!")]\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @return Color[]\n */\n #[Query]\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n'))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * This class contains 2 factories to create Product objects.\n * The "getProduct" method is used by default to map "Product" classes.\n * The "createProduct" method will generate another input type named "CreateProductInput"\n */\nclass ProductFactory\n{\n // ...\n\n /**\n * This factory will be used by default to map "Product" classes.\n * @Factory(name="ProductRefInput", default=true)\n */\n public function getProduct(string $id): Product\n {\n return $this->productRepository->findById($id);\n }\n /**\n * We specify a name for this input type explicitly.\n * @Factory(name="CreateProductInput", default=false)\n */\n public function createProduct(string $name, string $type): Product\n {\n return new Product($name, $type);\n }\n}\n\nclass ProductController\n{\n /**\n * The "createProduct" factory will be used for this mutation.\n *\n * @Mutation\n * @UseInputType(for="$product", inputType="CreateProductInput!")\n */\n public function saveProduct(Product $product): Product\n {\n // ...\n }\n\n /**\n * The default "getProduct" factory will be used for this query.\n *\n * @Query\n * @return Color[]\n */\n public function availableColors(Product $product): array\n {\n // ...\n }\n}\n')))),(0,l.kt)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.kt)("small",null,"Available in GraphQLite 4.0+"),(0,l.kt)("p",null,"GraphQLite will automatically map all your parameters to an input type.\nBut sometimes, you might want to avoid exposing some of those parameters."),(0,l.kt)("p",null,"Image your ",(0,l.kt)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.kt)("inlineCode",{parentName:"p"},"lazyLoad")," parameter. This parameter is interesting when you call\ndirectly the function in PHP because you can have some level of optimisation on your code. But it is not something that\nyou want to expose in the GraphQL API. Let's hide it!"),(0,l.kt)(r.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},"#[Factory]\npublic function getProductById(\n string $id,\n #[HideParameter]\n bool $lazyLoad = true\n ): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n"))),(0,l.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory()\n * @HideParameter(for="$lazyLoad")\n */\npublic function getProductById(string $id, bool $lazyLoad = true): Product\n{\n return $this->productRepository->findById($id, $lazyLoad);\n}\n')))),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.kt)("p",null,"To be able to hide an argument, the argument must have a default value."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e6858589.718aeb82.js b/assets/js/e6858589.d3810fdf.js similarity index 92% rename from assets/js/e6858589.718aeb82.js rename to assets/js/e6858589.d3810fdf.js index e75e9f42fe..74cea930dc 100644 --- a/assets/js/e6858589.718aeb82.js +++ b/assets/js/e6858589.d3810fdf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3049],{6803:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>r,metadata:()=>a,toc:()=>d});var n=o(7462),i=(o(7294),o(3905));o(1839);const r={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-3.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-3.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/3.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/troubleshooting.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-3.0/docs",previous:{title:"Custom output types",permalink:"/docs/3.0/custom-output-types"},next:{title:"Annotations reference",permalink:"/docs/3.0/annotations_reference"}},l={},d=[],u={toc:d},c="wrapper";function p(e){let{components:t,...o}=e;return(0,i.kt)(c,(0,n.Z)({},u,o,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,i.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3049],{6803:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>r,metadata:()=>a,toc:()=>d});var n=o(7462),i=(o(7294),o(3905));o(1839);const r={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-3.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-3.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/3.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/troubleshooting.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},sidebar:"version-3.0/docs",previous:{title:"Custom output types",permalink:"/docs/3.0/custom-output-types"},next:{title:"Annotations reference",permalink:"/docs/3.0/annotations_reference"}},l={},d=[],u={toc:d},c="wrapper";function p(e){let{components:t,...o}=e;return(0,i.kt)(c,(0,n.Z)({},u,o,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,i.kt)("p",null,"Webonyx's GraphQL library tends to use a very deep stack.\nThis error does not necessarily mean your code is going into an infinite loop.\nSimply try to increase the maximum allowed nesting level in your XDebug conf:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e688cd7e.fccecb47.js b/assets/js/e688cd7e.ac81e355.js similarity index 99% rename from assets/js/e688cd7e.fccecb47.js rename to assets/js/e688cd7e.ac81e355.js index b258fb49f4..65dfc71a5d 100644 --- a/assets/js/e688cd7e.fccecb47.js +++ b/assets/js/e688cd7e.ac81e355.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3679],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},4639:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},i=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-6.1/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-6.1/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/doctrine-annotations-attributes.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/migrating"},next:{title:"Annotations reference",permalink:"/docs/annotations-reference"}},l={},u=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],c={toc:u},p="wrapper";function d(t){let{components:e,...n}=t;return(0,r.kt)(p,(0,a.Z)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3679],{5162:(t,e,n)=>{n.d(e,{Z:()=>i});var a=n(7294),r=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(t){let{children:e,hidden:n,className:i}=t;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},e)}},4866:(t,e,n)=>{n.d(e,{Z:()=>w});var a=n(7462),r=n(7294),o=n(6010),i=n(2466),s=n(6550),l=n(1980),u=n(7392),c=n(12);function p(t){return function(t){return r.Children.map(t,(t=>{if(!t||(0,r.isValidElement)(t)&&function(t){const{props:e}=t;return!!e&&"object"==typeof e&&"value"in e}(t))return t;throw new Error(`Docusaurus error: Bad child <${"string"==typeof t.type?t.type:t.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(t).map((t=>{let{props:{value:e,label:n,attributes:a,default:r}}=t;return{value:e,label:n,attributes:a,default:r}}))}function d(t){const{values:e,children:n}=t;return(0,r.useMemo)((()=>{const t=e??p(n);return function(t){const e=(0,u.l)(t,((t,e)=>t.value===e.value));if(e.length>0)throw new Error(`Docusaurus error: Duplicate values "${e.map((t=>t.value)).join(", ")}" found in . Every value needs to be unique.`)}(t),t}),[e,n])}function h(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function b(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.k6)(),o=function(t){let{queryString:e=!1,groupId:n}=t;if("string"==typeof e)return e;if(!1===e)return null;if(!0===e&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:e,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((t=>{if(!o)return;const e=new URLSearchParams(a.location.search);e.set(o,t),a.replace({...a.location,search:e.toString()})}),[o,a])]}function m(t){const{defaultValue:e,queryString:n=!1,groupId:a}=t,o=d(t),[i,s]=(0,r.useState)((()=>function(t){let{defaultValue:e,tabValues:n}=t;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(e){if(!h({value:e,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${e}" but none of its children has the corresponding value. Available values are: ${n.map((t=>t.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return e}const a=n.find((t=>t.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:e,tabValues:o}))),[l,u]=b({queryString:n,groupId:a}),[p,m]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),f=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!h({value:t,tabValues:o}))throw new Error(`Can't select invalid tab value=${t}`);s(t),u(t),m(t)}),[u,m,o]),tabValues:o}}var f=n(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=t=>{const e=t.currentTarget,n=c.indexOf(e),a=u[n].value;a!==s&&(p(e),l(a))},h=t=>{let e=null;switch(t.key){case"Enter":d(t);break;case"ArrowRight":{const n=c.indexOf(t.currentTarget)+1;e=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(t.currentTarget)-1;e=c[n]??c[c.length-1];break}}e?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===e?0:-1,"aria-selected":s===e,key:e,ref:t=>c.push(t),onKeyDown:h,onClick:d},i,{className:(0,o.Z)("tabs__item",g.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function y(t){let{lazy:e,children:n,selectedValue:a}=t;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(e){const t=o.find((t=>t.props.value===a));return t?(0,r.cloneElement)(t,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((t,e)=>(0,r.cloneElement)(t,{key:e,hidden:t.props.value!==a}))))}function v(t){const e=m(t);return r.createElement("div",{className:(0,o.Z)("tabs-container",g.tabList)},r.createElement(k,(0,a.Z)({},t,e)),r.createElement(y,(0,a.Z)({},t,e)))}function w(t){const e=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(e)},t))}},4639:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(7462),r=(n(7294),n(3905));n(1839),n(4866),n(5162);const o={id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},i=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-6.1/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-6.1/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/doctrine-annotations-attributes.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/migrating"},next:{title:"Annotations reference",permalink:"/docs/annotations-reference"}},l={},u=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2},{value:"Migrating from Doctrine annotations to PHP 8 attributes",id:"migrating-from-doctrine-annotations-to-php-8-attributes",level:2}],c={toc:u},p="wrapper";function d(t){let{components:e,...n}=t;return(0,r.kt)(p,(0,a.Z)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.kt)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.kt)("p",null,'Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the ',(0,r.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.kt)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"Please note that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.kt)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.kt)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.kt)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("strong",null,"Heads up!"),(0,r.kt)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.kt)("ul",null,(0,r.kt)("li",null,"PhpStorm via the ",(0,r.kt)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.kt)("li",null,"Eclipse via the ",(0,r.kt)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.kt)("li",null,"Netbeans has native support")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.kt)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.kt)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.kt)("p",null,"The same code can be written this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.kt)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.kt)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.kt)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.kt)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.kt)("p",null,"They support the same attributes too."),(0,r.kt)("p",null,"A few notable differences:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.kt)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.kt)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.kt)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.kt)("li",{parentName:"ul"},'PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.')),(0,r.kt)("p",null,"Let's take an example with the ",(0,r.kt)("a",{parentName:"p",href:"/docs/autowiring"},(0,r.kt)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,r.kt)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.kt)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="rector.php"',title:'"rector.php"'},"import(SetList::CODE_QUALITY);\n\n // Set parameters\n $parameters = $containerConfigurator->parameters();\n $parameters->set(Option::PATHS, [\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ]);\n\n $services = $containerConfigurator->services();\n\n // @Validate and @Assertion are part of other libraries, include if necessary\n $services->set(AnnotationToAttributeRector::class)\n ->configure([\n new AnnotationToAttribute(GraphQLite\\Query::class),\n new AnnotationToAttribute(GraphQLite\\Mutation::class),\n new AnnotationToAttribute(GraphQLite\\Type::class),\n new AnnotationToAttribute(GraphQLite\\ExtendType::class),\n new AnnotationToAttribute(GraphQLite\\Input::class),\n new AnnotationToAttribute(GraphQLite\\Field::class),\n new AnnotationToAttribute(GraphQLite\\SourceField::class),\n new AnnotationToAttribute(GraphQLite\\MagicField::class),\n new AnnotationToAttribute(GraphQLite\\Logged::class),\n new AnnotationToAttribute(GraphQLite\\Right::class),\n new AnnotationToAttribute(GraphQLite\\FailWith::class),\n new AnnotationToAttribute(GraphQLite\\HideIfUnauthorized::class),\n new AnnotationToAttribute(GraphQLite\\InjectUser::class),\n new AnnotationToAttribute(GraphQLite\\Security::class),\n new AnnotationToAttribute(GraphQLite\\Factory::class),\n new AnnotationToAttribute(GraphQLite\\UseInputType::class),\n new AnnotationToAttribute(GraphQLite\\Decorate::class),\n new AnnotationToAttribute(GraphQLite\\Autowire::class),\n new AnnotationToAttribute(GraphQLite\\HideParameter::class),\n new AnnotationToAttribute(GraphQLite\\EnumType::class),\n ]);\n};\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e7672013.23ce00f7.js b/assets/js/e7672013.97c9e5e1.js similarity index 98% rename from assets/js/e7672013.23ce00f7.js rename to assets/js/e7672013.97c9e5e1.js index 4db519b8e5..7cdf77568c 100644 --- a/assets/js/e7672013.23ce00f7.js +++ b/assets/js/e7672013.97c9e5e1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[947],{6807:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},r=void 0,s={unversionedId:"authentication_authorization",id:"version-3.0/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-3.0/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/3.0/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/authentication_authorization.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-3.0/docs",previous:{title:"Extending a type",permalink:"/docs/3.0/extend_type"},next:{title:"External type declaration",permalink:"/docs/3.0/external_type_declaration"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Constant schemas",id:"constant-schemas",level:2},{value:"Connecting GraphQLite to your framework's security module",id:"connecting-graphqlite-to-your-frameworks-security-module",level:2}],h={toc:l},c="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,i.kt)("p",null,"GraphQLite offers some control over what a user can do with your API based on authentication (whether the user\nis logged or not) or authorization (what rights the user have)."),(0,i.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle, it is up to you to connect this feature to your framework's security mechanism.",(0,i.kt)("br",null),"See ",(0,i.kt)("a",{href:"#connecting-graphqlite-to-your-framework-s-security-module"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.kt)("h2",{id:"logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.kt)("p",null,"GraphQLite exposes two annotations (",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"In the example above, the query ",(0,i.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("div",{class:"alert alert--info"},"The query/mutation/field will NOT be part of the GraphQL schema if the current user is not logged or has not the requested right."),(0,i.kt)("h2",{id:"constant-schemas"},"Constant schemas"),(0,i.kt)("p",null,"By default, the schema will vary based on who is connected. This can be a problem with some GraphQL clients as the schema\nis changing from one user to another."),(0,i.kt)("p",null,"If you want to keep a constant schema, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation that contains the value that\nwill be returned for user with insufficient rights."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("h2",{id:"connecting-graphqlite-to-your-frameworks-security-module"},"Connecting GraphQLite to your framework's security module"),(0,i.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for user using GraphQLite through the Symfony Bundle"),(0,i.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,i.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,i.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged.\n *\n * @return bool\n */\n public function isLogged(): bool;\n}\n')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right".\n *\n * @param string $right\n * @return bool\n */\n public function isAllowed(string $right): bool;\n}\n')))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[947],{6807:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},r=void 0,s={unversionedId:"authentication_authorization",id:"version-3.0/authentication_authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-3.0/authentication_authorization.mdx",sourceDirName:".",slug:"/authentication_authorization",permalink:"/docs/3.0/authentication_authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/authentication_authorization.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication_authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization",original_id:"authentication_authorization"},sidebar:"version-3.0/docs",previous:{title:"Extending a type",permalink:"/docs/3.0/extend_type"},next:{title:"External type declaration",permalink:"/docs/3.0/external_type_declaration"}},u={},l=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Constant schemas",id:"constant-schemas",level:2},{value:"Connecting GraphQLite to your framework's security module",id:"connecting-graphqlite-to-your-frameworks-security-module",level:2}],h={toc:l},c="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,i.kt)("p",null,"GraphQLite offers some control over what a user can do with your API based on authentication (whether the user\nis logged or not) or authorization (what rights the user have)."),(0,i.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle, it is up to you to connect this feature to your framework's security mechanism.",(0,i.kt)("br",null),"See ",(0,i.kt)("a",{href:"#connecting-graphqlite-to-your-framework-s-security-module"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.kt)("h2",{id:"logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.kt)("p",null,"GraphQLite exposes two annotations (",(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("p",null,"In the example above, the query ",(0,i.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.kt)("div",{class:"alert alert--info"},"The query/mutation/field will NOT be part of the GraphQL schema if the current user is not logged or has not the requested right."),(0,i.kt)("h2",{id:"constant-schemas"},"Constant schemas"),(0,i.kt)("p",null,"By default, the schema will vary based on who is connected. This can be a problem with some GraphQL clients as the schema\nis changing from one user to another."),(0,i.kt)("p",null,"If you want to keep a constant schema, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation that contains the value that\nwill be returned for user with insufficient rights."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')),(0,i.kt)("h2",{id:"connecting-graphqlite-to-your-frameworks-security-module"},"Connecting GraphQLite to your framework's security module"),(0,i.kt)("div",{class:"alert alert--info"},"This step is NOT necessary for user using GraphQLite through the Symfony Bundle"),(0,i.kt)("p",null,"GraphQLite needs to know if a user is logged or not, and what rights it has.\nBut this is specific of the framework you use."),(0,i.kt)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,i.kt)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthenticationServiceInterface\n{\n /**\n * Returns true if the "current" user is logged.\n *\n * @return bool\n */\n public function isLogged(): bool;\n}\n')),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'interface AuthorizationServiceInterface\n{\n /**\n * Returns true if the "current" user has access to the right "$right".\n *\n * @param string $right\n * @return bool\n */\n public function isAllowed(string $right): bool;\n}\n')))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e7ffb4b4.8656b35a.js b/assets/js/e7ffb4b4.12bd1fa6.js similarity index 97% rename from assets/js/e7ffb4b4.8656b35a.js rename to assets/js/e7ffb4b4.12bd1fa6.js index 6fe78e20b5..05598befb3 100644 --- a/assets/js/e7ffb4b4.8656b35a.js +++ b/assets/js/e7ffb4b4.12bd1fa6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5780],{4284:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-3.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-3.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/3.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/getting-started.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-3.0/docs",previous:{title:"GraphQLite",permalink:"/docs/3.0/"},next:{title:"Symfony bundle",permalink:"/docs/3.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5780],{4284:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>g,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},o=void 0,s={unversionedId:"getting-started",id:"version-3.0/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-3.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/3.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/getting-started.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started",original_id:"getting-started"},sidebar:"version-3.0/docs",previous:{title:"GraphQLite",permalink:"/docs/3.0/"},next:{title:"Symfony bundle",permalink:"/docs/3.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/3.0/other-frameworks"},"Get started with another framework (or no framework)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e806c7bf.aacdb54b.js b/assets/js/e806c7bf.4e7e4404.js similarity index 99% rename from assets/js/e806c7bf.aacdb54b.js rename to assets/js/e806c7bf.4e7e4404.js index 34b92d9925..477ab1727e 100644 --- a/assets/js/e806c7bf.aacdb54b.js +++ b/assets/js/e806c7bf.4e7e4404.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2850],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2103:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/docs/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/next/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/laravel-package-advanced.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/next/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/next/internals"}},p={},c=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3},{value:"Export the schema from the CLI",id:"export-the-schema-from-the-cli",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,r.kt)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,r.kt)("p",null,"The extension comes with a special command: ",(0,r.kt)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,r.kt)("p",null,"Usage:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,r.kt)("p",null,"This will export your GraphQL schema in SDL format. You can use this exported schema to import it in other\ntools (like graphql-codegen)."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2850],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==o&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",v.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",v.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},2103:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},s=void 0,u={unversionedId:"laravel-package-advanced",id:"laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/docs/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/next/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/laravel-package-advanced.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},sidebar:"docs",previous:{title:"Symfony specific features",permalink:"/docs/next/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/next/internals"}},p={},c=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3},{value:"Export the schema from the CLI",id:"export-the-schema-from-the-cli",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Be advised!")," This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the ",(0,r.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.kt)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.kt)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.kt)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n #[Mutation]\n public function createUser(\n #[Validate("email|unique:users")]\n string $email,\n #[Validate("gte:8")]\n string $password\n ): User\n {\n // ...\n }\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Laravel\\Annotations\\Validate;\n\nclass MyController\n{\n /**\n * @Mutation\n * @Validate(for="$email", rule="email|unique:users")\n * @Validate(for="$password", rule="gte:8")\n */\n public function createUser(string $email, string $password): User\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.kt)("p",null,'If a validation fails to pass, the message will be printed in the "errors" section and you will get a HTTP 400 status code:'),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "The email must be a valid email address.",\n "extensions": {\n "argument": "email",\n "category": "Validate"\n }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password",\n "category": "Validate"\n }\n }\n ]\n}\n')),(0,r.kt)("p",null,"You can use any validation rule described in ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.kt)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.kt)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\LengthAwarePaginator\n {\n return Product::paginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.kt)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},'products {\n items { # The items for the selected page\n id\n name\n }\n totalCount # The total count of items.\n lastPage # Get the page number of the last available page.\n firstItem # Get the "index" of the first item being paginated.\n lastItem # Get the "index" of the last item being paginated.\n hasMorePages # Determine if there are more items in the data source.\n perPage # Get the number of items shown per page.\n hasPages # Determine if there are enough items to split into multiple pages.\n currentPage # Determine the current page being paginated.\n isEmpty # Determine if the list of items is empty or not.\n isNotEmpty # Determine if the list of items is not empty.\n}\n')),(0,r.kt)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.kt)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.kt)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.kt)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.kt)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.kt)("p",null,"Note: if you are using ",(0,r.kt)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.kt)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Illuminate\\Pagination\\Paginator\n {\n return Product::simplePaginate(15);\n }\n}\n")))),(0,r.kt)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.kt)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.kt)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.kt)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.kt)("p",null,"Eloquent uses PHP magic properties to expose your database records.\nBecause Eloquent relies on magic properties, it is quite rare for an Eloquent model to have proper getters and setters."),(0,r.kt)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.kt)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Type]\n#[MagicField(name: "id", outputType: "ID!")]\n#[MagicField(name: "name", phpType: "string")]\n#[MagicField(name: "categories", phpType: "Category[]")]\nclass Product extends Model\n{\n}\n'))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type()\n * @MagicField(name="id", outputType="ID!")\n * @MagicField(name="name", phpType="string")\n * @MagicField(name="categories", phpType="Category[]")\n */\nclass Product extends Model\n{\n}\n')))),(0,r.kt)("p",null,'Please note that since the properties are "magic", they don\'t have a type. Therefore,\nyou need to pass either the "outputType" attribute with the GraphQL type matching the property,\nor the "phpType" attribute with the PHP type matching the property.'),(0,r.kt)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.kt)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * Get the phone record associated with the user.\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n")),(0,r.kt)("p",null,"It would be tempting to put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.kt)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.kt)("p",null,"In short:"),(0,r.kt)("div",{class:"alert alert--danger"},"This does not work:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n /**\n * @Field\n */\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,r.kt)("div",{class:"alert alert--success"},"This works:",(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @MagicField(name="phone", phpType="App\\\\Phone")\n */\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,r.kt)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,r.kt)("p",null,"The extension comes with a special command: ",(0,r.kt)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,r.kt)("p",null,"Usage:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,r.kt)("p",null,"This will export your GraphQL schema in SDL format. You can use this exported schema to import it in other\ntools (like graphql-codegen)."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e91daeb9.4c4cd16d.js b/assets/js/e91daeb9.0403b08d.js similarity index 98% rename from assets/js/e91daeb9.4c4cd16d.js rename to assets/js/e91daeb9.0403b08d.js index 883ca131fe..0637119dbb 100644 --- a/assets/js/e91daeb9.4c4cd16d.js +++ b/assets/js/e91daeb9.0403b08d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[678],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=h({queryString:a,groupId:n}),[p,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),f(e)}),[u,f,l]),tabValues:l}}var g=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5042:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const l={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,i={unversionedId:"pagination",id:"version-6.1/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-6.1/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/pagination.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/file-uploads"},next:{title:"Custom types",permalink:"/docs/custom-types"}},s={},u=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],c={toc:u},p="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(p,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[678],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),i=a(6550),s=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,u]=h({queryString:a,groupId:n}),[p,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),f(e)}),[u,f,l]),tabValues:l}}var g=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},5042:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(7462),r=(a(7294),a(3905));a(1839),a(4866),a(5162);const l={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,i={unversionedId:"pagination",id:"version-6.1/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-6.1/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/pagination.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/file-uploads"},next:{title:"Custom types",permalink:"/docs/custom-types"}},s={},u=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],c={toc:u},p="wrapper";function d(e){let{components:t,...a}=e;return(0,r.kt)(p,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eaa287f0.d2a25c10.js b/assets/js/eaa287f0.914edb1c.js similarity index 99% rename from assets/js/eaa287f0.d2a25c10.js rename to assets/js/eaa287f0.914edb1c.js index 83eaf3d5ee..6ab17169c5 100644 --- a/assets/js/eaa287f0.d2a25c10.js +++ b/assets/js/eaa287f0.914edb1c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9722],{3397:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=t(7462),i=(t(7294),t(3905));t(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-6.1/changelog",title:"Changelog",description:"6.1.0",source:"@site/versioned_docs/version-6.1/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/CHANGELOG.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/semver"}},d={},p=[{value:"6.1.0",id:"610",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-3",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,i.kt)(u,(0,n.Z)({},s,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"610"},"6.1.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Drop support for php 7.4")),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-3"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9722],{3397:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var n=t(7462),i=(t(7294),t(3905));t(1839);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-6.1/changelog",title:"Changelog",description:"6.1.0",source:"@site/versioned_docs/version-6.1/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/CHANGELOG.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/semver"}},d={},p=[{value:"6.1.0",id:"610",level:2},{value:"Breaking change:",id:"breaking-change",level:4},{value:"5.0.0",id:"500",level:2},{value:"Dependencies:",id:"dependencies",level:4},{value:"4.3.0",id:"430",level:2},{value:"Breaking change:",id:"breaking-change-1",level:4},{value:"Minor changes:",id:"minor-changes",level:4},{value:"4.2.0",id:"420",level:2},{value:"Breaking change:",id:"breaking-change-2",level:4},{value:"New features:",id:"new-features",level:4},{value:"4.1.0",id:"410",level:2},{value:"Breaking change:",id:"breaking-change-3",level:4},{value:"New features:",id:"new-features-1",level:4},{value:"Minor changes:",id:"minor-changes-1",level:4},{value:"Miscellaneous:",id:"miscellaneous",level:4},{value:"4.0.0",id:"400",level:2},{value:"New features:",id:"new-features-2",level:4},{value:"Symfony:",id:"symfony",level:4},{value:"Laravel:",id:"laravel",level:4},{value:"Internals:",id:"internals",level:4}],s={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,i.kt)(u,(0,n.Z)({},s,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"610"},"6.1.0"),(0,i.kt)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Drop support for php 7.4")),(0,i.kt)("h2",{id:"500"},"5.0.0"),(0,i.kt)("h4",{id:"dependencies"},"Dependencies:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.kt)("h2",{id:"430"},"4.3.0"),(0,i.kt)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The method ",(0,i.kt)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.kt)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.kt)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.kt)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.kt)("h2",{id:"420"},"4.2.0"),(0,i.kt)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.kt)("p",null,"The method signature for ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLOutputType(Type $type, ?OutputType $subType, $reflector, DocBlock $docBlockObj): OutputType;\n\n/**\n * @param \\ReflectionMethod|\\ReflectionProperty $reflector\n */\npublic function toGraphQLInputType(Type $type, ?InputType $subType, string $argumentName, $reflector, DocBlock $docBlockObj): InputType;\n")),(0,i.kt)("h4",{id:"new-features"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.kt)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.kt)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.kt)("a",{parentName:"li",href:"/docs/input-types#input-attribute"},"example"),"."),(0,i.kt)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.kt)("a",{parentName:"li",href:"/docs/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.kt)("inlineCode",{parentName:"li"},"for"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"description"),"."),(0,i.kt)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.kt)("h2",{id:"410"},"4.1.0"),(0,i.kt)("h4",{id:"breaking-change-3"},"Breaking change:"),(0,i.kt)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("strong",{parentName:"li"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL input types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.kt)("h4",{id:"new-features-1"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.kt)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.kt)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.kt)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from ",(0,i.kt)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.kt)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.kt)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.kt)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.kt)("h2",{id:"400"},"4.0.0"),(0,i.kt)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.kt)("h4",{id:"new-features-2"},"New features:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"You can directly ",(0,i.kt)("a",{parentName:"li",href:"/docs/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.kt)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.kt)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.kt)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.kt)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.kt)("li",{parentName:"ul"},"Improved security handling:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.kt)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.kt)("a",{parentName:"li",href:"/docs/fine-grained-security"},"marked accessible or not depending on the context"),'.\nFor instance, you can restrict access to the field "viewsCount" of the type ',(0,i.kt)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.kt)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.kt)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.kt)("li",{parentName:"ul"},"Performance:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can inject the ",(0,i.kt)("a",{parentName:"li",href:"/docs/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.kt)("li",{parentName:"ul"},"You can use the ",(0,i.kt)("a",{parentName:"li",href:"/docs/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.kt)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"You can throw ",(0,i.kt)("a",{parentName:"li",href:"/docs/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.kt)("li",{parentName:"ul"},"You can force input types using ",(0,i.kt)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.kt)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.kt)("a",{parentName:"li",href:"/docs/extend-input-type"},"the new ",(0,i.kt)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.kt)("li",{parentName:"ul"},"In a factory, you can ",(0,i.kt)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.kt)("p",null,"Many extension points have been added"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'Added a "root type mapper" (useful to map scalar types to PHP types or to add custom annotations related to resolvers)'),(0,i.kt)("li",{parentName:"ul"},"Added ",(0,i.kt)("a",{parentName:"li",href:"/docs/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.kt)("li",{parentName:"ul"},"Added a ",(0,i.kt)("a",{parentName:"li",href:"/docs/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.kt)("p",null,"New framework specific features:"),(0,i.kt)("h4",{id:"symfony"},"Symfony:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.kt)("h4",{id:"laravel"},"Laravel:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.kt)("h4",{id:"internals"},"Internals:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.kt)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.kt)("em",{parentName:"li"},"root type mappers"),")"),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.kt)("li",{parentName:"ul"},"Overall, there is not much in common internally between 4.x and 3.x. 4.x is much more flexible with many more hook points\nthan 3.x. Try it out!")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eb333c39.4fed5623.js b/assets/js/eb333c39.7bcf779f.js similarity index 98% rename from assets/js/eb333c39.4fed5623.js rename to assets/js/eb333c39.7bcf779f.js index 88c37be342..6d987c7462 100644 --- a/assets/js/eb333c39.4fed5623.js +++ b/assets/js/eb333c39.7bcf779f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4626],{3306:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>p});var r=t(7462),o=(t(7294),t(3905));t(1839);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},i=void 0,s={unversionedId:"error-handling",id:"version-4.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.0/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/error_handling.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.0/validation"}},l={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],c={toc:p},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.kt)(h,(0,r.Z)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,o.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.kt)("p",null,"By default, when you throw a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,o.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,o.kt)("p",null,"will generate:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,o.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.kt)("p",null,"will generate:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.kt)("p",null,"Rather that throwing the base ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.kt)("p",null,"Any exception that implements interface ",(0,o.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,o.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,o.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")),(0,o.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.kt)("p",null,"Actually, the ",(0,o.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.kt)("p",null,"If an exception that does not implement ",(0,o.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.kt)("p",null,"You can ",(0,o.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,o.kt)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony"),", ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package"},"Laravel"),")."),(0,o.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4626],{3306:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>p});var r=t(7462),o=(t(7294),t(3905));t(1839);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},i=void 0,s={unversionedId:"error-handling",id:"version-4.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.0/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/error_handling.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.0/validation"}},l={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],c={toc:p},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.kt)(h,(0,r.Z)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,o.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.kt)("p",null,"By default, when you throw a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,o.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,o.kt)("p",null,"will generate:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,o.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.kt)("p",null,"will generate:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.kt)("p",null,"Rather that throwing the base ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.kt)("p",null,"Any exception that implements interface ",(0,o.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,o.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,o.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")),(0,o.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,o.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.kt)("p",null,"Actually, the ",(0,o.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.kt)("p",null,"If an exception that does not implement ",(0,o.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.kt)("p",null,"You can ",(0,o.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,o.kt)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony"),", ",(0,o.kt)("a",{parentName:"p",href:"/docs/4.0/laravel-package"},"Laravel"),")."),(0,o.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eca0cf35.5a0afeae.js b/assets/js/eca0cf35.810abbea.js similarity index 99% rename from assets/js/eca0cf35.5a0afeae.js rename to assets/js/eca0cf35.810abbea.js index aa2c2087da..c539c1e1d7 100644 --- a/assets/js/eca0cf35.5a0afeae.js +++ b/assets/js/eca0cf35.810abbea.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[228],{9745:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},o=void 0,l={unversionedId:"extend_type",id:"version-3.0/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-3.0/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/3.0/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-3.0/docs",previous:{title:"Type mapping",permalink:"/docs/3.0/type_mapping"},next:{title:"Authentication and authorization",permalink:"/docs/3.0/authentication_authorization"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,i.kt)("a",{href:"inheritance"},"Inheritance")," section"),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,i.kt)("p",null,"Using ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,i.kt)("p",null,"Let's break this sample:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"With the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,i.kt)("p",null,'Using the "',(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[228],{9745:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=n(7462),i=(n(7294),n(3905));n(1839);const r={id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},o=void 0,l={unversionedId:"extend_type",id:"version-3.0/extend_type",title:"Extending a type",description:"Fields exposed in a GraphQL type do not need to be all part of the same class.",source:"@site/versioned_docs/version-3.0/extend_type.mdx",sourceDirName:".",slug:"/extend_type",permalink:"/docs/3.0/extend_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_type",title:"Extending a type",sidebar_label:"Extending a type",original_id:"extend_type"},sidebar:"version-3.0/docs",previous:{title:"Type mapping",permalink:"/docs/3.0/type_mapping"},next:{title:"Authentication and authorization",permalink:"/docs/3.0/authentication_authorization"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.kt)(c,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.kt)("div",{class:"alert alert--info"},"Extending a type has nothing to do with type inheritance. If you are looking for a way to expose a class and its children classes, have a look at the ",(0,i.kt)("a",{href:"inheritance"},"Inheritance")," section"),(0,i.kt)("p",null,"Let's assume you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.kt)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.kt)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getId(): string\n {\n return $this->id;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"// You need to use a service to get the name of the product in the correct language.\n$name = $translationService->getProductName($productId, $language);\n")),(0,i.kt)("p",null,"Using ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.kt)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Types;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\ExtendType;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse App\\Entities\\Product;\n\n/**\n * @ExtendType(class=Product::class)\n */\nclass ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n /**\n * @Field()\n */\n public function getName(Product $product, string $language): string\n {\n return $this->translationService->getProductName($product->getId(), $language);\n }\n}\n")),(0,i.kt)("p",null,"Let's break this sample:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.kt)("p",null,"With the ",(0,i.kt)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"class ProductType\n{\n private $translationService;\n\n public function __construct(TranslationServiceInterface $translationService)\n {\n $this->translationService = $translationService;\n }\n\n // ...\n}\n")),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.kt)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.kt)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.kt)("div",{class:"alert alert--warning"},(0,i.kt)("strong",null,"Heads up!")," The ",(0,i.kt)("code",null,"ProductType")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,i.kt)("br",null),(0,i.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field()\n */\npublic function getName(Product $product, string $language): string\n{\n return $this->translationService->getProductName($product->getId(), $language);\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.kt)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.kt)("p",null,'Take a close look at the signature. The first parameter is the "resolved object" we are working on.\nAny additional parameters are used as arguments.'),(0,i.kt)("p",null,'Using the "',(0,i.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"Type language"),'" notation, we defined a type extension for\nthe GraphQL "Product" type:'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.kt)("div",{class:"alert alert--success"},"Type extension is a very powerful tool. Use it to add fields that needs to be computed from services not available in the entity."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ece9cf29.725eb00a.js b/assets/js/ece9cf29.3ee571cb.js similarity index 98% rename from assets/js/ece9cf29.725eb00a.js rename to assets/js/ece9cf29.3ee571cb.js index f226d904f3..b97fec41af 100644 --- a/assets/js/ece9cf29.725eb00a.js +++ b/assets/js/ece9cf29.3ee571cb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2535],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},319:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-4.2/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.2/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.2/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/pagination.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-4.2/docs",previous:{title:"File uploads",permalink:"/docs/4.2/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.2/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2535],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),s=a(6550),i=a(1980),u=a(7392),c=a(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??p(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:a,groupId:n}),[p,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),g(e)}),[u,g,l]),tabValues:l}}var f=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.o5)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:m,onClick:d},o,{className:(0,l.Z)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":s===t})}),a??t)})))}function k(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(k,(0,n.Z)({},e,t)))}function w(e){const t=(0,f.Z)();return r.createElement(y,(0,n.Z)({key:String(t)},e))}},319:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-4.2/pagination",title:"Paginating large result sets",description:"It is quite common to have to paginate over large result sets.",source:"@site/versioned_docs/version-4.2/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/4.2/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/pagination.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"version-4.2/docs",previous:{title:"File uploads",permalink:"/docs/4.2/file-uploads"},next:{title:"Custom types",permalink:"/docs/4.2/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.kt)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.kt)("p",null,"Porpaginas is a set of PHP interfaces that can be implemented by result iterators. It comes with a native support for\nPHP arrays, Doctrine and ",(0,r.kt)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.kt)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.kt)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"You will need to install the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"In your query, simply return a class that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @return Product[]\n */\n #[Query]\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Query\n * @return Product[]\n */\n public function products(): Porpaginas\\Result\n {\n // Some code that returns a list of products\n\n // If you are using Doctrine, something like:\n return new Porpaginas\\Doctrine\\ORM\\ORMQueryResult($doctrineQuery);\n }\n}\n")))),(0,r.kt)("p",null,"Notice that:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.kt)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.kt)("li",{parentName:"ul"},"you MUST add a ",(0,r.kt)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.kt)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.kt)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.kt)("p",null,'The "count" field returns the ',(0,r.kt)("strong",{parentName:"p"},"total count")," of items."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ed0c0463.5d6c04b1.js b/assets/js/ed0c0463.e4fbc445.js similarity index 98% rename from assets/js/ed0c0463.5d6c04b1.js rename to assets/js/ed0c0463.e4fbc445.js index ea0a1eeecf..725872f9ad 100644 --- a/assets/js/ed0c0463.5d6c04b1.js +++ b/assets/js/ed0c0463.e4fbc445.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3597],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4953:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-5.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-5.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/5.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/file-uploads.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-5.0/docs",previous:{title:"Prefetching records",permalink:"/docs/5.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/5.0/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3597],{5162:(e,t,a)=>{a.d(t,{Z:()=>o});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:a,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,o),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>w});var n=a(7462),r=a(7294),l=a(6010),o=a(2466),u=a(6550),i=a(1980),s=a(7392),p=a(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function c(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??d(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function m(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:a}=e;const n=(0,u.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,i._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=c(e),[o,u]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[i,s]=h({queryString:a,groupId:n}),[d,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&u(b)}),[b]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var b=a(2389);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),c=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==u&&(d(t),i(n))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>p.push(e),onKeyDown:m,onClick:c},o,{className:(0,l.Z)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":u===t})}),a??t)})))}function y(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function k(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",g.tabList)},r.createElement(v,(0,n.Z)({},e,t)),r.createElement(y,(0,n.Z)({},e,t)))}function w(e){const t=(0,b.Z)();return r.createElement(k,(0,n.Z)({key:String(t)},e))}},4953:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),o=a(5162);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-5.0/file-uploads",title:"File uploads",description:"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed",source:"@site/versioned_docs/version-5.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/5.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/file-uploads.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"version-5.0/docs",previous:{title:"Prefetching records",permalink:"/docs/5.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/5.0/pagination"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"GraphQL does not support natively the notion of file uploads, but an extension to the GraphQL protocol was proposed\nto add support for ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.kt)("h2",{id:"installation"},"Installation"),(0,r.kt)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.kt)("p",null,"You must start by installing this package:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.kt)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.kt)("p",null,"If you are using our Symfony bundle, the file upload middleware is managed by the bundle. You have nothing to do\nand can start using it right away."),(0,r.kt)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.kt)("p",null,"In order to use this, you must first be sure that the ",(0,r.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.kt)("p",null,"Simply add ",(0,r.kt)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.kt)("h3",{id:"if-you-are-using-another-framework-not-compatible-with-psr-15"},"If you are using another framework not compatible with PSR-15"),(0,r.kt)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.kt)("h2",{id:"usage"},"Usage"),(0,r.kt)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.kt)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n #[Mutation]\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyController\n{\n /**\n * @Mutation\n */\n public function saveDocument(string $name, UploadedFileInterface $file): Document\n {\n // Some code that saves the document.\n $file->moveTo($someDir);\n }\n}\n")))),(0,r.kt)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec#client"},"jaydenseric/graphql-multipart-request-spec")," for a list of compatible clients."),(0,r.kt)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"mutation upload($file: Upload!) {\n upload(file: $file)\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eec7caa6.77f86541.js b/assets/js/eec7caa6.8b087ab1.js similarity index 99% rename from assets/js/eec7caa6.77f86541.js rename to assets/js/eec7caa6.8b087ab1.js index c35319ff63..a2c6e624f0 100644 --- a/assets/js/eec7caa6.77f86541.js +++ b/assets/js/eec7caa6.8b087ab1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8337],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},764:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/docs/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/next/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/authentication-authorization.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/next/validation"},next:{title:"Fine grained security",permalink:"/docs/next/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/next/implementing-security"},'"authentication service" configured in GraphQLite'),". If user is not authenticated and\nparameter's type is not nullable, an authorization exception is thrown, similar to ",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation. Beware of ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/annotations-reference"},"it's limitations"),"."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8337],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},764:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/docs/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/next/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/authentication-authorization.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/next/validation"},next:{title:"Fine grained security",permalink:"/docs/next/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/next/implementing-security"},'"authentication service" configured in GraphQLite'),". If user is not authenticated and\nparameter's type is not nullable, an authorization exception is thrown, similar to ",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," annotation."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation. Beware of ",(0,r.kt)("a",{parentName:"p",href:"/docs/next/annotations-reference"},"it's limitations"),"."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f07f4757.7a9be42a.js b/assets/js/f07f4757.22b41240.js similarity index 99% rename from assets/js/f07f4757.7a9be42a.js rename to assets/js/f07f4757.22b41240.js index e80df98a6d..083b4aa30f 100644 --- a/assets/js/f07f4757.7a9be42a.js +++ b/assets/js/f07f4757.22b41240.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7517],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},5595:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-3.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-3.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/3.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance-interfaces.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7517],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var a=t(7294),r=t(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>N});var a=t(7462),r=t(7294),l=t(6010),i=t(2466),s=t(6550),p=t(1980),c=t(7392),o=t(12);function u(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:r}}=e;return{value:n,label:t,attributes:a,default:r}}))}function m(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??u(t);return function(e){const n=(0,c.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,s.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,p._X)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function f(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[p,c]=h({queryString:t,groupId:a}),[u,f]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),f(e)}),[c,f,l]),tabValues:l}}var g=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=c[t].value;a!==s&&(u(n),p(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":s===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,a.Z)({},e,n)),r.createElement(y,(0,a.Z)({},e,n)))}function N(e){const n=(0,g.Z)();return r.createElement(v,(0,a.Z)({key:String(n)},e))}},5595:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var a=t(7462),r=(t(7294),t(3905)),l=(t(1839),t(4866)),i=t(5162);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-3.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-3.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/3.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance-interfaces.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function h(e){let{components:n,...t}=e;return(0,r.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,r.kt)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.kt)("p",null,"Some of your entities may extend other entities. GraphQLite will do its best to represent this hierarchy of objects in GraphQL using interfaces."),(0,r.kt)("p",null,"Let's say you have two classes, ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass Contact\n{\n // ...\n}\n\n#[Type]\nclass User extends Contact\n{\n // ...\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass Contact\n{\n // ...\n}\n\n/**\n * @Type\n */\nclass User extends Contact\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")))),(0,r.kt)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.kt)("p",null,"Written in ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype Contact implements ContactInterface {\n // List of fields declared in Contact class\n}\n\ntype User implements ContactInterface {\n // List of fields declared in Contact and User classes\n}\n")),(0,r.kt)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.kt)("p",null,"The GraphQL ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.kt)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.kt)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.kt)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.kt)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\ninterface UserInterface\n{\n /**\n * @Field\n */\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.kt)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.kt)("p",null,'You don\'t have to do anything special to implement an interface in your GraphQL types.\nSimply "implement" the interface in PHP and you are done!'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.kt)("p",null,"This will translate in GraphQL schema as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.kt)("p",null,"Please note that you do not need to put the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.kt)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.kt)("p",null,"You don't have to explicitly put a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no #Type attribute\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n #[Query]\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Look, this class has no @Type annotation\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class UserController\n{\n /**\n * @Query()\n */\n public function getUser(): UserInterface // This will work!\n {\n // ...\n }\n}\n")))),(0,r.kt)("div",{class:"alert alert--info"},'If GraphQLite cannot find a proper GraphQL Object type implementing an interface, it will create an object type "on the fly".'),(0,r.kt)("p",null,"In the example above, because the ",(0,r.kt)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.kt)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.kt)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f2710c27.65bf6004.js b/assets/js/f2710c27.25c40395.js similarity index 98% rename from assets/js/f2710c27.65bf6004.js rename to assets/js/f2710c27.25c40395.js index ab9cb02dd4..2b58c93b41 100644 --- a/assets/js/f2710c27.65bf6004.js +++ b/assets/js/f2710c27.25c40395.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5403],{7387:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/docs/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/next/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/migrating.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/next/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/next/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5403],{7387:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>m,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(7462),i=(a(7294),a(3905));a(1839);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/docs/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/next/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/migrating.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/next/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"}},s={},d=[{value:"Migrating from v4.0 to v4.1",id:"migrating-from-v40-to-v41",level:2},{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],p={toc:d},u="wrapper";function m(e){let{components:t,...a}=e;return(0,i.kt)(u,(0,n.Z)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.kt)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.kt)("a",{parentName:"p",href:"/docs/next/semver"},"semantic versioning")," for more details."),(0,i.kt)("p",null,"There is one exception though: the ",(0,i.kt)("strong",{parentName:"p"},"ecodev/graphql-upload"),' package (used to get support for file uploads in GraphQL\ninput types) is now a "recommended" dependency only.\nIf you are using GraphQL file uploads, you need to add ',(0,i.kt)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.kt)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.kt)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.kt)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.kt)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.kt)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.kt)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.kt)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.kt)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.kt)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.kt)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.kt)("li",{parentName:"ul"},"In GraphQLite v3, the default was to hide a field from the schema if a user has no access to it.\nIn GraphQLite v4, the default is to still show this field, but to throw an error if the user makes a query on it\n(this way, the schema is the same for all users). If you want the old mode, use the new\n",(0,i.kt)("a",{parentName:"li",href:"/docs/next/annotations-reference#hideifunauthorized-annotation"},(0,i.kt)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.kt)("li",{parentName:"ul"},"If you are using the Symfony bundle, the Laravel package or the Universal module, you must also upgrade those to 4.0.\nThese package will take care of the wiring for you. Apart for upgrading the packages, you have nothing to do."),(0,i.kt)("li",{parentName:"ul"},"If you are relying on the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.kt)("p",null,"On the other hand, if you are a power user and if you are wiring GraphQLite services yourself (without using the\n",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.kt)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.kt)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.kt)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"HydratorInterface")," and all implementations are gone. When returning an input object from a TypeMapper, the object\nmust now implement the ",(0,i.kt)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.kt)("p",null,"Note: we strongly recommend to use the Symfony bundle, the Laravel package, the Universal module or the SchemaManager\nto bootstrap GraphQLite. Wiring directly GraphQLite classes (like the ",(0,i.kt)("inlineCode",{parentName:"p"},"FieldsBuilder"),") into your container is not recommended,\nas the signature of the constructor of those classes may vary from one minor release to another.\nUse the ",(0,i.kt)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f309eabc.bdafe4fb.js b/assets/js/f309eabc.486245e5.js similarity index 99% rename from assets/js/f309eabc.bdafe4fb.js rename to assets/js/f309eabc.486245e5.js index 60c7ae3930..39bcdf0219 100644 --- a/assets/js/f309eabc.bdafe4fb.js +++ b/assets/js/f309eabc.486245e5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8854],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>k});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function k(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},806:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/docs/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/next/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/error-handling.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/next/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/next/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/next/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/next/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8854],{5162:(e,n,t)=>{t.d(n,{Z:()=>i});var r=t(7294),a=t(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:t,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,a.Z)(o.tabItem,i),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>k});var r=t(7462),a=t(7294),o=t(6010),i=t(2466),l=t(6550),s=t(1980),u=t(7392),c=t(12);function p(e){return function(e){return a.Children.map(e,(e=>{if(!e||(0,a.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:r,default:a}}=e;return{value:n,label:t,attributes:r,default:a}}))}function h(e){const{values:n,children:t}=e;return(0,a.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.k6)(),o=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(o),(0,a.useCallback)((e=>{if(!o)return;const n=new URLSearchParams(r.location.search);n.set(o,e),r.replace({...r.location,search:n.toString()})}),[o,r])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:r}=e,o=h(e),[i,l]=(0,a.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const r=t.find((e=>e.default))??t[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:t,groupId:r}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Nk)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),f=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:i,selectValue:(0,a.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var f=t(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function x(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),r=u[t].value;r!==l&&(p(n),s(r))},d=e=>{let n=null;switch(e.key){case"Enter":h(e);break;case"ArrowRight":{const t=c.indexOf(e.currentTarget)+1;n=c[t]??c[0];break}case"ArrowLeft":{const t=c.indexOf(e.currentTarget)-1;n=c[t]??c[c.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.Z)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===n})}),t??n)})))}function y(e){let{lazy:n,children:t,selectedValue:r}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,a.cloneElement)(e,{className:"margin-top--md"}):null}return a.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,a.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function w(e){const n=g(e);return a.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},a.createElement(x,(0,r.Z)({},e,n)),a.createElement(y,(0,r.Z)({},e,n)))}function k(e){const n=(0,f.Z)();return a.createElement(w,(0,r.Z)({key:String(n)},e))}},806:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(7462),a=(t(7294),t(3905)),o=(t(1839),t(4866)),i=t(5162);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,u={unversionedId:"error-handling",id:"error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/docs/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/next/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/error-handling.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/next/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/next/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function m(e){let{components:n,...t}=e;return(0,a.kt)(d,(0,r.Z)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Name for character with ID 1002 could not be fetched.",\n "locations": [ { "line": 6, "column": 7 } ],\n "path": [ "hero", "heroFriends", 1, "name" ],\n "extensions": {\n "category": "Exception"\n }\n }\n ]\n}\n')),(0,a.kt)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.kt)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.kt)("p",null,"By default, when you throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.kt)("p",null,"If your exception code is in the 4xx - 5xx range, the exception code will be used as an HTTP status code."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.kt)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.kt)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.kt)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.kt)("p",null,'By default, GraphQLite adds a "category" entry in the "extensions section". You can customize the category with the\n4th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Not found",\n "extensions": {\n "category": "NOT_FOUND"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.kt)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.kt)("p",null,"will generate:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "category": "VALIDATION",\n "field": "name"\n }\n }\n ]\n}\n')),(0,a.kt)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.kt)("p",null,"Rather that throwing the base ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.kt)("p",null,"Any exception that implements interface ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},'class ValidationException extends Exception implements GraphQLExceptionInterface\n{\n /**\n * Returns true when exception message is safe to be displayed to a client.\n */\n public function isClientSafe(): bool\n {\n return true;\n }\n\n /**\n * Returns string describing a category of the error.\n *\n * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.\n */\n public function getCategory(): string\n {\n return \'VALIDATION\';\n }\n\n /**\n * Returns the "extensions" object attached to the GraphQL error.\n *\n * @return array\n */\n public function getExtensions(): array\n {\n return [];\n }\n}\n')),(0,a.kt)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.kt)("p",null,"Sometimes, you need to display several errors in the response. But of course, at any given point in your code, you can\nthrow only one exception."),(0,a.kt)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n#[Query]\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n"))),(0,a.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException;\n\n/**\n * @Query\n */\npublic function createProduct(string $name, float $price): Product\n{\n $exceptions = new GraphQLAggregateException();\n\n if ($name === '') {\n $exceptions->add(new GraphQLException('Name cannot be empty', 400, null, 'VALIDATION'));\n }\n if ($price <= 0) {\n $exceptions->add(new GraphQLException('Price must be positive', 400, null, 'VALIDATION'));\n }\n\n if ($exceptions->hasExceptions()) {\n throw $exceptions;\n }\n}\n")))),(0,a.kt)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.kt)("p",null,"GraphQLite is based on the wonderful webonyx/GraphQL-PHP library. Therefore, the Webonyx exception mechanism can\nalso be used in GraphQLite. This means you can throw a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.kt)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.kt)("p",null,"Actually, the ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.kt)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.kt)("p",null,"If an exception that does not implement ",(0,a.kt)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.kt)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.kt)("p",null,"You can ",(0,a.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#debugging-tools"},"change the underlying behaviour of Webonyx to catch any exception and turn them into GraphQL errors"),".\nThe way you adjust the error settings depends on the framework you are using (",(0,a.kt)("a",{parentName:"p",href:"/docs/next/symfony-bundle"},"Symfony"),", ",(0,a.kt)("a",{parentName:"p",href:"/docs/next/laravel-package"},"Laravel"),")."),(0,a.kt)("div",{class:"alert alert--info"},'To be clear: we strongly discourage changing this setting. We strongly believe that the default "RETHROW_UNSAFE_EXCEPTIONS" setting of Webonyx is the only sane setting (only putting in "errors" section exceptions designed for GraphQL).'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f48e2589.0060b545.js b/assets/js/f48e2589.cd474b0d.js similarity index 94% rename from assets/js/f48e2589.0060b545.js rename to assets/js/f48e2589.cd474b0d.js index d8d69b78ef..53021bdf5d 100644 --- a/assets/js/f48e2589.0060b545.js +++ b/assets/js/f48e2589.cd474b0d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8842],{5623:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-6.1/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-6.1/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/getting-started.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/"},next:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8842],{5623:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>m,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(7462),i=(a(7294),a(3905));a(1839);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-6.1/getting-started",title:"Getting started",description:"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to",source:"@site/versioned_docs/version-6.1/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/getting-started.md",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/"},next:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function m(t){let{components:e,...a}=t;return(0,i.kt)(c,(0,r.Z)({},p,a,{components:e,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"GraphQLite is a framework agnostic library. You can use it in any PHP project as long as you know how to\ninject services in your favorite framework's container."),(0,i.kt)("p",null,"Currently, we provide bundle/packages to help you get started with Symfony, Laravel and any framework compatible\nwith container-interop/service-provider."),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/symfony-bundle"},"Get started with Symfony")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/laravel-package"},"Get started with Laravel")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"/docs/other-frameworks"},"Get started with another framework (or no framework)"))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f4e1d1ba.10e90bde.js b/assets/js/f4e1d1ba.c968124d.js similarity index 98% rename from assets/js/f4e1d1ba.10e90bde.js rename to assets/js/f4e1d1ba.c968124d.js index 2626574556..ce324c66b7 100644 --- a/assets/js/f4e1d1ba.10e90bde.js +++ b/assets/js/f4e1d1ba.c968124d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9327],{6070:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.2/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.2/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/field-middlewares.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-4.2/docs",previous:{title:"Custom types",permalink:"/docs/4.2/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.2/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9327],{6070:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(7462),a=(t(7294),t(3905));t(1839);const l={id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.2/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.2/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/field-middlewares.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"version-4.2/docs",previous:{title:"Custom types",permalink:"/docs/4.2/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/4.2/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.kt)(p,(0,i.Z)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("small",null,"Available in GraphQLite 4.0+"),(0,a.kt)("p",null,"Just like the ",(0,a.kt)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.kt)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.kt)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.kt)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.kt)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.kt)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.kt)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.kt)("p",null,(0,a.kt)("img",{src:t(6068).Z,width:"960",height:"540"})),(0,a.kt)("p",null,"Each middleware is passed a ",(0,a.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\QueryFieldDescriptor")," instance. This object contains all the\nparameters used to initialize the field (like the return type, the list of arguments, the resolver to be used, etc...)"),(0,a.kt)("p",null,"Each middleware must return a ",(0,a.kt)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * Your middleware must implement this interface.\n */\ninterface FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition;\n}\n")),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"class QueryFieldDescriptor\n{\n public function getName() { /* ... */ }\n public function setName(string $name) { /* ... */ }\n public function getType() { /* ... */ }\n public function setType($type): void { /* ... */ }\n public function getParameters(): array { /* ... */ }\n public function setParameters(array $parameters): void { /* ... */ }\n public function getPrefetchParameters(): array { /* ... */ }\n public function setPrefetchParameters(array $prefetchParameters): void { /* ... */ }\n public function getPrefetchMethodName(): ?string { /* ... */ }\n public function setPrefetchMethodName(?string $prefetchMethodName): void { /* ... */ }\n public function setCallable(callable $callable): void { /* ... */ }\n public function setTargetMethodOnSource(?string $targetMethodOnSource): void { /* ... */ }\n public function isInjectSource(): bool { /* ... */ }\n public function setInjectSource(bool $injectSource): void { /* ... */ }\n public function getComment(): ?string { /* ... */ }\n public function setComment(?string $comment): void { /* ... */ }\n public function getMiddlewareAnnotations(): MiddlewareAnnotations { /* ... */ }\n public function setMiddlewareAnnotations(MiddlewareAnnotations $middlewareAnnotations): void { /* ... */ }\n public function getOriginalResolver(): ResolverInterface { /* ... */ }\n public function getResolver(): callable { /* ... */ }\n public function setResolver(callable $resolver): void { /* ... */ }\n}\n")),(0,a.kt)("p",null,"The role of a middleware is to analyze the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.kt)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.kt)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.kt)("inlineCode",{parentName:"p"},"null"),"."),(0,a.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.kt)("p",null,"Take a look at the ",(0,a.kt)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.kt)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.kt)("p",null,"Let's imagine you want to add a ",(0,a.kt)("inlineCode",{parentName:"p"},"@OnlyDebug")," annotation that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.kt)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.kt)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library (for PHP 7+) and/or by PHP 8 attributes."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="OnlyDebug.php"',title:'"OnlyDebug.php"'},'namespace App\\Annotations;\n\nuse Attribute;\nuse TheCodingMachine\\GraphQLite\\Annotations\\MiddlewareAnnotationInterface;\n\n/**\n * @Annotation\n * @Target({"METHOD", "ANNOTATION"})\n */\n#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n')),(0,a.kt)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.kt)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),'. This interface is a "marker" interface. It does not have any methods. It is just used to tell GraphQLite that this annotation is to be used by middlewares.'),(0,a.kt)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Middlewares;\n\nuse App\\Annotations\\OnlyDebug;\nuse TheCodingMachine\\GraphQLite\\Middlewares\\FieldMiddlewareInterface;\nuse GraphQL\\Type\\Definition\\FieldDefinition;\nuse TheCodingMachine\\GraphQLite\\QueryFieldDescriptor;\n\n/**\n * Middleware in charge of hiding a field if it is annotated with @OnlyDebug and the DEBUG constant is not set\n */\nclass OnlyDebugFieldMiddleware implements FieldMiddlewareInterface\n{\n public function process(QueryFieldDescriptor $queryFieldDescriptor, FieldHandlerInterface $fieldHandler): ?FieldDefinition\n {\n $annotations = $queryFieldDescriptor->getMiddlewareAnnotations();\n\n /**\n * @var OnlyDebug $onlyDebug\n */\n $onlyDebug = $annotations->getAnnotationByType(OnlyDebug::class);\n\n if ($onlyDebug !== null && !DEBUG) {\n // If the onlyDebug annotation is present, returns null.\n // Returning null will hide the field.\n return null;\n }\n\n // Otherwise, let's continue the middleware pipe without touching anything.\n return $fieldHandler->handle($queryFieldDescriptor);\n }\n}\n")),(0,a.kt)("p",null,"The final thing we have to do is to register the middleware."),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"Assuming you are using the ",(0,a.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.kt)("pre",{parentName:"li"},(0,a.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.kt)("li",{parentName:"ul"},(0,a.kt)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.kt)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},6068:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/f5b0a435.61ff95b6.js b/assets/js/f5b0a435.b78baf4d.js similarity index 99% rename from assets/js/f5b0a435.61ff95b6.js rename to assets/js/f5b0a435.b78baf4d.js index 1b0a04ae34..4b7ecf05d8 100644 --- a/assets/js/f5b0a435.61ff95b6.js +++ b/assets/js/f5b0a435.b78baf4d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2905],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>T});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),i=t(6550),s=t(1980),u=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,i.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,i]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[s,u]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=t(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=u[t].value;a!==i&&(c(n),s(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===n?0:-1,"aria-selected":i===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":i===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function T(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},5769:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},s=void 0,u={unversionedId:"type_mapping",id:"version-4.1/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.1/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/4.1/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/type_mapping.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-4.1/docs",previous:{title:"Mutations",permalink:"/docs/4.1/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.1/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.1/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2905],{5162:(e,n,t)=>{t.d(n,{Z:()=>r});var a=t(7294),p=t(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:t},n)}},4866:(e,n,t)=>{t.d(n,{Z:()=>T});var a=t(7462),p=t(7294),l=t(6010),r=t(2466),i=t(6550),s=t(1980),u=t(7392),o=t(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:n}=e;return!!n&&"object"==typeof n&&"value"in n}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:n,label:t,attributes:a,default:p}}=e;return{value:n,label:t,attributes:a,default:p}}))}function m(e){const{values:n,children:t}=e;return(0,p.useMemo)((()=>{const e=n??c(t);return function(e){const n=(0,u.l)(e,((e,n)=>e.value===n.value));if(n.length>0)throw new Error(`Docusaurus error: Duplicate values "${n.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[n,t])}function d(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function h(e){let{queryString:n=!1,groupId:t}=e;const a=(0,i.k6)(),l=function(e){let{queryString:n=!1,groupId:t}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!t)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return t??null}({queryString:n,groupId:t});return[(0,s._X)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(a.location.search);n.set(l,e),a.replace({...a.location,search:n.toString()})}),[l,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=m(e),[r,i]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" but none of its children has the corresponding value. Available values are: ${t.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return n}const a=t.find((e=>e.default))??t[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:n,tabValues:l}))),[s,u]=h({queryString:t,groupId:a}),[c,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,l]=(0,o.Nk)(t);return[a,(0,p.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),g=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=t(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:n,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const n=e.currentTarget,t=o.indexOf(n),a=u[t].value;a!==i&&(c(n),s(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const t=o.indexOf(e.currentTarget)+1;n=o[t]??o[0];break}case"ArrowLeft":{const t=o.indexOf(e.currentTarget)-1;n=o[t]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:i===n?0:-1,"aria-selected":i===n,key:n,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":i===n})}),t??n)})))}function b(e){let{lazy:n,children:t,selectedValue:a}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,n)=>(0,p.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,n)),p.createElement(b,(0,a.Z)({},e,n)))}function T(e){const n=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(n)},e))}},5769:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=t(7462),p=(t(7294),t(3905)),l=(t(1839),t(4866)),r=t(5162);const i={id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},s=void 0,u={unversionedId:"type_mapping",id:"version-4.1/type_mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.1/type_mapping.mdx",sourceDirName:".",slug:"/type_mapping",permalink:"/docs/4.1/type_mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/type_mapping.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type_mapping",title:"Type mapping",sidebar_label:"Type mapping",original_id:"type_mapping"},sidebar:"version-4.1/docs",previous:{title:"Mutations",permalink:"/docs/4.1/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.1/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:n,...t}=e;return(0,p.kt)(d,(0,a.Z)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.1/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f7c03581.d7cc737a.js b/assets/js/f7c03581.c8a60a0f.js similarity index 98% rename from assets/js/f7c03581.d7cc737a.js rename to assets/js/f7c03581.c8a60a0f.js index 69a8722c5b..b93f7e0a90 100644 --- a/assets/js/f7c03581.d7cc737a.js +++ b/assets/js/f7c03581.c8a60a0f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[680],{8829:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},r=void 0,s={unversionedId:"fine-grained-security",id:"version-6.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-6.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/fine-grained-security.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"}},l={},u=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],c={toc:u},p="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(p,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"If the ",(0,i.kt)("a",{parentName:"p",href:"/docs/authentication-authorization#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"Using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.kt)("li",{parentName:"ul"},"...")),(0,i.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.kt)("code",null,"@Security")," annotation and Symfony's ",(0,i.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.kt)("h2",{id:"the-is_granted-function"},"The ",(0,i.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.kt)("p",null,"is similar to"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.kt)("p",null,"In addition, the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"In the example above, the ",(0,i.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,i.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.kt)("a",{parentName:"p",href:"/docs/authentication-authorization#not-throwing-errors"},(0,i.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"You cannot use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')),(0,i.kt)("h2",{id:"available-scope"},"Available scope"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,i.kt)("p",null,"If you are using Symfony, you will ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.kt)("p",null,"If you are using Laravel, you will ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.kt)("p",null,"If you are using another framework, you need to know that the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.kt)("a",{parentName:"p",href:"/docs/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[680],{8829:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(7462),i=(n(7294),n(3905));n(1839);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},r=void 0,s={unversionedId:"fine-grained-security",id:"version-6.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-6.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/fine-grained-security.mdx",tags:[],version:"6.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"}},l={},u=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],c={toc:u},p="wrapper";function d(e){let{components:t,...n}=e;return(0,i.kt)(p,(0,a.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"If the ",(0,i.kt)("a",{parentName:"p",href:"/docs/authentication-authorization#logged-and-right-annotations"},(0,i.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"Using the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.kt)("li",{parentName:"ul"},"...")),(0,i.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.kt)("code",null,"@Security")," annotation and Symfony's ",(0,i.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.kt)("h2",{id:"the-is_granted-function"},"The ",(0,i.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.kt)("p",null,"Use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.kt)("p",null,"is similar to"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.kt)("p",null,"In addition, the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n")),(0,i.kt)("p",null,"In the example above, the ",(0,i.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n')),(0,i.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,i.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n")),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.kt)("a",{parentName:"p",href:"/docs/authentication-authorization#not-throwing-errors"},(0,i.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.kt)("p",null,"You cannot use the ",(0,i.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')),(0,i.kt)("h2",{id:"available-scope"},"Available scope"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,i.kt)("p",null,"If you are using Symfony, you will ",(0,i.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.kt)("p",null,"If you are using Laravel, you will ",(0,i.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.kt)("p",null,"If you are using another framework, you need to know that the ",(0,i.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.kt)("a",{parentName:"p",href:"/docs/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f9063551.9c8bf406.js b/assets/js/f9063551.32b958d4.js similarity index 98% rename from assets/js/f9063551.9c8bf406.js rename to assets/js/f9063551.32b958d4.js index fdaa2d4174..11d5688690 100644 --- a/assets/js/f9063551.9c8bf406.js +++ b/assets/js/f9063551.32b958d4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6364],{273:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.2/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.2/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/argument-resolving.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.2/docs",previous:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6364],{273:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(7462),r=(a(7294),a(3905));a(1839);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-4.2/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/4.2/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/argument-resolving.md",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.2/docs",previous:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function u(e){let{components:t,...a}=e;return(0,r.kt)(d,(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("p",null,"Using a ",(0,r.kt)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.kt)("div",{class:"alert alert--info"},"Use a parameter middleware if you want to alter the way arguments are injected in a method or if you want to alter the way input types are imported (for instance if you want to add a validation step)"),(0,r.kt)("p",null,"As an example, GraphQLite uses ",(0,r.kt)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.kt)("pre",{parentName:"li"},(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.kt)("p",{parentName:"li"},"In the query above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.kt)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("p",{parentName:"li"},"Perform validation with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.kt)("p",null,(0,r.kt)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.kt)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.kt)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"a PHP ",(0,r.kt)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.kt)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Annotations\\ParameterAnnotations")," instance. This is a collection of all custom annotations that apply to this specific argument (more on that later)"),(0,r.kt)("li",{parentName:"ul"},"a ",(0,r.kt)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.kt)("p",null,"Parameter resolution is done in 2 passes."),(0,r.kt)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.kt)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"interface ParameterMiddlewareInterface\n{\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface;\n}\n")),(0,r.kt)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.kt)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.kt)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.kt)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.kt)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.kt)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.kt)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.kt)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.kt)("p",null,"The annotation looks like this:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this annotation to autowire a service from the container into a given parameter of a field/query/mutation.\n *\n * @Annotation\n */\n#[Attribute(Attribute::TARGET_PARAMETER)]\nclass Autowire implements ParameterAnnotationInterface\n{\n /**\n * @var string\n */\n public $for;\n\n /**\n * The getTarget method must return the name of the argument\n */\n public function getTarget(): string\n {\n return $this->for;\n }\n}\n")),(0,r.kt)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.kt)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter middleware class"',title:'"Parameter',middleware:!0,'class"':!0},"class ContainerParameterHandler implements ParameterMiddlewareInterface\n{\n /** @var ContainerInterface */\n private $container;\n\n public function __construct(ContainerInterface $container)\n {\n $this->container = $container;\n }\n\n public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, ?Type $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface\n {\n // The $parameterAnnotations object can be used to fetch any annotation implementing ParameterAnnotationInterface\n $autowire = $parameterAnnotations->getAnnotationByType(Autowire::class);\n\n if ($autowire === null) {\n // If there are no annotation, this middleware cannot handle the parameter. Let's ask\n // the next middleware in the chain (using the $next object)\n return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations);\n }\n\n // We found a @Autowire annotation, let's return a parameter resolver.\n return new ContainerParameter($this->container, $parameter->getType());\n }\n}\n")),(0,r.kt)("p",null,"The last step is to write the actual parameter resolver."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php",metastring:'title="Parameter resolver class"',title:'"Parameter',resolver:!0,'class"':!0},'/**\n * A parameter filled from the container.\n */\nclass ContainerParameter implements ParameterInterface\n{\n /** @var ContainerInterface */\n private $container;\n /** @var string */\n private $identifier;\n\n public function __construct(ContainerInterface $container, string $identifier)\n {\n $this->container = $container;\n $this->identifier = $identifier;\n }\n\n /**\n * The "resolver" returns the actual value that will be fed to the function.\n */\n public function resolve(?object $source, array $args, $context, ResolveInfo $info)\n {\n return $this->container->get($this->identifier);\n }\n}\n')),(0,r.kt)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.kt)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.kt)("p",null,"You can register your own parameter middlewares using the ",(0,r.kt)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.kt)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f94b062c.d8b886a7.js b/assets/js/f94b062c.8920a9cb.js similarity index 99% rename from assets/js/f94b062c.d8b886a7.js rename to assets/js/f94b062c.8920a9cb.js index a80f57cffd..e0e73fd14b 100644 --- a/assets/js/f94b062c.d8b886a7.js +++ b/assets/js/f94b062c.8920a9cb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8577],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},8067:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-5.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-5.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/5.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/fine-grained-security.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-5.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/5.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/5.0/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8577],{5162:(e,t,a)=>{a.d(t,{Z:()=>l});var n=a(7294),r=a(6010);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:t,hidden:a,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,l),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>N});var n=a(7462),r=a(7294),o=a(6010),l=a(2466),i=a(6550),s=a(1980),u=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.k6)(),o=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,s._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(n.location.search);t.set(o,e),n.replace({...n.location,search:t.toString()})}),[o,n])]}function g(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,o=d(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:o}))),[s,u]=m({queryString:a,groupId:n}),[c,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),y=(()=>{const e=s??c;return h({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&i(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),g(e)}),[u,g,o]),tabValues:o}}var y=a(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=u[a].value;n!==i&&(c(t),s(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:l}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},l,{className:(0,o.Z)("tabs__item",k.tabItem,l?.className,{"tabs__item--active":i===t})}),a??t)})))}function b(e){let{lazy:t,children:a,selectedValue:n}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",k.tabList)},r.createElement(f,(0,n.Z)({},e,t)),r.createElement(b,(0,n.Z)({},e,t)))}function N(e){const t=(0,y.Z)();return r.createElement(v,(0,n.Z)({key:String(t)},e))}},8067:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),o=(a(1839),a(4866)),l=a(5162);const i={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-5.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-5.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/5.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/fine-grained-security.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"version-5.0/docs",previous:{title:"Authentication and authorization",permalink:"/docs/5.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/5.0/implementing-security"}},p={},c=[{value:"Using the @Security annotation",id:"using-the-security-annotation",level:2},{value:"The is_granted function",id:"the-is_granted-function",level:2},{value:"Accessing method parameters",id:"accessing-method-parameters",level:2},{value:"Setting HTTP code and error message",id:"setting-http-code-and-error-message",level:2},{value:"Setting a default value",id:"setting-a-default-value",level:2},{value:"Accessing the user",id:"accessing-the-user",level:2},{value:"Accessing the current object",id:"accessing-the-current-object",level:2},{value:"Available scope",id:"available-scope",level:2},{value:"How to restrict access to a given resource",id:"how-to-restrict-access-to-a-given-resource",level:2}],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"If the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"Using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.kt)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.kt)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.kt)("li",{parentName:"ul"},"...")),(0,r.kt)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n#[Query]\n#[Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Security;\n\n// ...\n\n/**\n * @Query\n * @Security(\"is_granted('ROLE_ADMIN') or is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("em",{parentName:"p"},"expression")," defined in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.kt)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.kt)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.kt)("code",null,"@Security")," annotation and Symfony's ",(0,r.kt)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.kt)("h2",{id:"the-is_granted-function"},"The ",(0,r.kt)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.kt)("p",null,"is similar to"),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.kt)("p",null,"In addition, the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(\"is_granted('POST_SHOW', post)\")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @Security(\"is_granted('POST_SHOW', post)\")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"In the example above, the ",(0,r.kt)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.kt)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.kt)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.kt)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "startDate < endDate", statusCode: 400, message: "End date must be after start date")]\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("startDate < endDate", statusCode=400, message="End date must be after start date")\n */\npublic function getPosts(DateTimeImmutable $startDate, DateTimeImmutable $endDate): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.kt)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security(expression: "is_granted(\'POST_SHOW\', post)", statusCode: 404, message: "Post not found (let\'s pretend the post does not exists!)")]\npublic function getPost(Post $post): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_granted(\'POST_SHOW\', post)", statusCode=404, message="Post not found (let\'s pretend the post does not exists!)")\n */\npublic function getPost(Post $post): array\n{\n // ...\n}\n')))),(0,r.kt)("p",null,"Note: since a single GraphQL call contain many errors, 2 errors might have conflicting HTTP status code.\nThe resulting status code is up to the GraphQL middleware you use. Most of the time, the status code with the\nhigher error code will be returned."),(0,r.kt)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.kt)("p",null,"If you do not want an error to be thrown when the security condition is not met, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Query]\n#[Security(expression: \"is_granted('CAN_SEE_MARGIN', this)\", failWith: null)]\npublic function getMargin(): float\n{\n // ...\n}\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n * @Security(\"is_granted('CAN_SEE_MARGIN', this)\", failWith=null)\n */\npublic function getMargin(): float\n{\n // ...\n}\n")))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#not-throwing-errors"},(0,r.kt)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.kt)("p",null,"You cannot use the ",(0,r.kt)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.kt)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.kt)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.kt)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @Security("is_logged() && user.age > 18")\n */\npublic function getNSFWImages(): array\n{\n // ...\n}\n')))),(0,r.kt)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.kt)("p",null,"You can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n #[Field]\n #[Security("this.canAccessBody(user)")]\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n'))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class Post {\n /**\n * @Field\n * @Security("this.canAccessBody(user)")\n */\n public function getBody(): array\n {\n // ...\n }\n\n public function canAccessBody(User $user): bool\n {\n // Some custom logic here\n }\n}\n')))),(0,r.kt)("h2",{id:"available-scope"},"Available scope"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.kt)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.kt)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.kt)(o.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(l.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.kt)(l.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.kt)("p",null,"If you are wondering how to configure these fine-grained permissions, this is not something that GraphQLite handles\nitself. Instead, this depends on the framework you are using."),(0,r.kt)("p",null,"If you are using Symfony, you will ",(0,r.kt)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.kt)("p",null,"If you are using Laravel, you will ",(0,r.kt)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.kt)("p",null,"If you are using another framework, you need to know that the ",(0,r.kt)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.kt)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.kt)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f9511b3d.b64acb7b.js b/assets/js/f9511b3d.67fd62ec.js similarity index 99% rename from assets/js/f9511b3d.b64acb7b.js rename to assets/js/f9511b3d.67fd62ec.js index b4871c895c..0bd23c5552 100644 --- a/assets/js/f9511b3d.b64acb7b.js +++ b/assets/js/f9511b3d.67fd62ec.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4274],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=m({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=u??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend_input_type",id:"version-3.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/3.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_input_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/extend_type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4274],{5162:(e,t,a)=>{a.d(t,{Z:()=>i});var n=a(7294),r=a(6010);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:a,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(l.tabItem,i),hidden:a},t)}},4866:(e,t,a)=>{a.d(t,{Z:()=>T});var n=a(7462),r=a(7294),l=a(6010),i=a(2466),o=a(6550),u=a(1980),s=a(7392),p=a(12);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:a,attributes:n,default:r}}=e;return{value:t,label:a,attributes:n,default:r}}))}function d(e){const{values:t,children:a}=e;return(0,r.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,a])}function h(e){let{value:t,tabValues:a}=e;return a.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:a}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!a)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return a??null}({queryString:t,groupId:a});return[(0,u._X)(l),(0,r.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(n.location.search);t.set(l,e),n.replace({...n.location,search:t.toString()})}),[l,n])]}function f(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[u,s]=m({queryString:a,groupId:n}),[c,f]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Nk)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),y=(()=>{const e=u??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var y=a(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.o5)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},h=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;t=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;t=p[a]??p[p.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:h,onClick:d},i,{className:(0,l.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(e){let{lazy:t,children:a,selectedValue:n}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===n));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==n}))))}function g(e){const t=f(e);return r.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},r.createElement(k,(0,n.Z)({},e,t)),r.createElement(v,(0,n.Z)({},e,t)))}function T(e){const t=(0,y.Z)();return r.createElement(g,(0,n.Z)({key:String(t)},e))}},592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(7462),r=(a(7294),a(3905)),l=(a(1839),a(4866)),i=a(5162);const o={id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"},u=void 0,s={unversionedId:"extend_input_type",id:"version-3.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/3.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_input_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},p={},c=[],d={toc:c},h="wrapper";function m(e){let{components:t,...a}=e;return(0,r.kt)(h,(0,n.Z)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("small",null,"Available in GraphQLite 4.0+"),(0,r.kt)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.kt)("code",null,"@Factory")," tag, ",(0,r.kt)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.kt)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.kt)("p",null,"Just like with output type (that can be ",(0,r.kt)("a",{parentName:"p",href:"/docs/3.0/extend_type"},"extended using the ",(0,r.kt)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.kt)("div",{class:"alert alert--info"},"The ",(0,r.kt)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.kt)("code",null,"@Factory")," method. This can happen if the ",(0,r.kt)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.kt)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.kt)("p",null,"Let's assume you have a ",(0,r.kt)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.kt)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n #[Factory]\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * @Factory()\n */\n public function createFilter(string $name): Filter\n {\n // Let's assume you have a flexible 'Filter' class that can accept any kind of filter\n $filter = new Filter();\n $filter->addFilter('name', $name);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,"Assuming you ",(0,r.kt)("strong",{parentName:"p"},"cannot"),' modify the code of this factory, you can still modify the GraphQL input type generated by\nadding a "decorator" around the factory.'),(0,r.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n #[Decorate(inputTypeName: \"FilterInput\")]\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n"))),(0,r.kt)(i.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"class MyDecorator\n{\n /**\n * @Decorate(inputTypeName=\"FilterInput\")\n */\n public function addTypeFilter(Filter $filter, string $type): Filter\n {\n $filter->addFilter('type', $type);\n return $filter;\n }\n}\n")))),(0,r.kt)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.kt)("p",null,"A few things to notice:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.kt)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.kt)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.kt)("li",{parentName:"ul"},"The ",(0,r.kt)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.kt)("inlineCode",{parentName:"li"},"inputTypeName")," attribute that contains the name of the GraphQL input type\nthat is decorated. If you did not specify this name in the ",(0,r.kt)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," The ",(0,r.kt)("code",null,"MyDecorator")," class must exist in the container of your application and the container identifier MUST be the fully qualified class name.",(0,r.kt)("br",null),(0,r.kt)("br",null),"If you are using the Symfony bundle (or a framework with autowiring like Laravel), this is usually not an issue as the container will automatically create the controller entry if you do not explicitly declare it."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f9af357c.12894983.js b/assets/js/f9af357c.323b5b1d.js similarity index 99% rename from assets/js/f9af357c.12894983.js rename to assets/js/f9af357c.323b5b1d.js index ce8d93f04b..caca4efc26 100644 --- a/assets/js/f9af357c.12894983.js +++ b/assets/js/f9af357c.323b5b1d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9862],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},911:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-5.0/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-5.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/5.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/authentication-authorization.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-5.0/docs",previous:{title:"User input validation",permalink:"/docs/5.0/validation"},next:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9862],{5162:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),r=n(6010);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:t,hidden:n,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(i.tabItem,o),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(7462),r=n(7294),i=n(6010),o=n(2466),l=n(6550),u=n(1980),s=n(7392),c=n(12);function d(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,s.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function h(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function m(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),i=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,u._X)(i),(0,r.useCallback)((e=>{if(!i)return;const t=new URLSearchParams(a.location.search);t.set(i,e),a.replace({...a.location,search:t.toString()})}),[i,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,i=p(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!h({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:i}))),[u,s]=m({queryString:n,groupId:a}),[d,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&l(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!h({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),s(e),g(e)}),[s,g,i]),tabValues:i}}var f=n(2389);const k={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==l&&(d(t),u(a))},h=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:h,onClick:p},o,{className:(0,i.Z)("tabs__item",k.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function y(e){let{lazy:t,children:n,selectedValue:a}=e;const i=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=i.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=g(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",k.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(y,(0,a.Z)({},e,t)))}function N(e){const t=(0,f.Z)();return r.createElement(v,(0,a.Z)({key:String(t)},e))}},911:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=n(7462),r=(n(7294),n(3905)),i=(n(1839),n(4866)),o=n(5162);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},u=void 0,s={unversionedId:"authentication-authorization",id:"version-5.0/authentication-authorization",title:"Authentication and authorization",description:"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields",source:"@site/versioned_docs/version-5.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/5.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/authentication-authorization.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-5.0/docs",previous:{title:"User input validation",permalink:"/docs/5.0/validation"},next:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function m(e){let{components:t,...n}=e;return(0,r.kt)(h,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some queries/mutations or fields\nreserved to some users."),(0,r.kt)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"based on authentication using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.kt)("li",{parentName:"ul"},"based on authorization using the ",(0,r.kt)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.kt)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.kt)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},(0,r.kt)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.kt)("div",{class:"alert alert--info"},"GraphQLite does not have its own security mechanism. Unless you're using our Symfony Bundle or our Laravel package, it is up to you to connect this feature to your framework's security mechanism.",(0,r.kt)("br",null),"See ",(0,r.kt)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.kt)("h2",{id:"logged-and-right-annotations"},(0,r.kt)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.kt)("p",null,"GraphQLite exposes two annotations (",(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Logged;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Right;\n\nclass UserController\n{\n /**\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"In the example above, the query ",(0,r.kt)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.kt)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.kt)("p",null,(0,r.kt)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/field, an error is raised and the query fails."),(0,r.kt)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.kt)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation he has no access to, you can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[FailWith(value: null)]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the value returned will be "null".\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @FailWith(null)\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.kt)("p",null,"Use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @return Product\n */\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n"))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\nuse TheCodingMachine\\GraphQLite\\Annotations\\InjectUser;\n\nclass ProductController\n{\n /**\n * @Query\n * @InjectUser(for="$user")\n * @return Product\n */\n public function product(int $id, User $user): Product\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.kt)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,r.kt)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.kt)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.kt)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/types available.\nSome will be available to him and some won't."),(0,r.kt)("p",null,"If you want to add an extra level of security (or if you want your schema to be kept secret to unauthorized users),\nyou can use the ",(0,r.kt)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.kt)(i.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.kt)(o.Z,{value:"php8",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @return User[]\n */\n #[Query]\n #[Logged]\n #[Right("CAN_VIEW_USER_LIST")]\n #[HideIfUnauthorized]\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n'))),(0,r.kt)(o.Z,{value:"php7",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},'class UserController\n{\n /**\n * If a user is not logged or if the user has not the right "CAN_VIEW_USER_LIST",\n * the schema will NOT contain the "users" query at all (so trying to call the\n * "users" query will result in a GraphQL "query not found" error.\n *\n * @Query\n * @Logged\n * @Right("CAN_VIEW_USER_LIST")\n * @HideIfUnauthorized()\n * @return User[]\n */\n public function users(int $limit, int $offset): array\n {\n // ...\n }\n}\n')))),(0,r.kt)("p",null,"While this is the most secured mode, it can have drawbacks when working with development tools\n(you need to be logged as admin to fetch the complete schema)."),(0,r.kt)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/fa1dd05c.5c0314a3.js b/assets/js/fa1dd05c.30a84796.js similarity index 98% rename from assets/js/fa1dd05c.5c0314a3.js rename to assets/js/fa1dd05c.30a84796.js index fa96cf9c42..f5c6c319a3 100644 --- a/assets/js/fa1dd05c.5c0314a3.js +++ b/assets/js/fa1dd05c.30a84796.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3497],{1396:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},l=void 0,o={unversionedId:"queries",id:"version-4.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/queries.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-4.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.0/mutations"}},s={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],u={toc:p},h="wrapper";function d(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3497],{1396:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=n(7462),r=(n(7294),n(3905));n(1839);const i={id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},l=void 0,o={unversionedId:"queries",id:"version-4.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-4.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/4.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/queries.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries",original_id:"queries"},sidebar:"version-4.0/docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/4.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/4.0/mutations"}},s={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"Testing the query",id:"testing-the-query",level:2},{value:"Query with a type",id:"query-with-a-type",level:2}],u={toc:p},h="wrapper";function d(e){let{components:t,...i}=e;return(0,r.kt)(h,(0,a.Z)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.kt)("em",{parentName:"p"},"controller")," classes."),(0,r.kt)("p",null,"Those classes must be in the controllers namespaces which has been defined when you configured GraphQLite.\nFor instance, in Symfony, the controllers namespace is ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.kt)("h2",{id:"simple-query"},"Simple query"),(0,r.kt)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.kt)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.kt)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.kt)("div",{class:"alert alert--warning"},(0,r.kt)("strong",null,"Heads up!")," If you are not using a framework with an autowiring container (like Symfony or Laravel), please be aware that the ",(0,r.kt)("code",null,"MyController")," class must exist in the container of your application. Furthermore, the identifier of the controller in the container MUST be the fully qualified class name of controller."),(0,r.kt)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.kt)("p",null,"The default GraphQL endpoint is ",(0,r.kt)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.kt)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.kt)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.kt)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.kt)("br",null),"Simply head to ",(0,r.kt)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.kt)("p",null,"Here a query using our simple ",(0,r.kt)("em",{parentName:"p"},"Hello World")," example:"),(0,r.kt)("p",null,(0,r.kt)("img",{src:n(1410).Z,width:"1132",height:"352"})),(0,r.kt)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.kt)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.kt)("p",null,"Let's assume you want to return a product:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass ProductController\n{\n /**\n * @Query\n */\n public function product(string $id): Product\n {\n // Some code that looks for a product and returns it.\n }\n}\n")),(0,r.kt)("p",null,"As the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.kt)("strong",{parentName:"p"},"public method"),"."),(0,r.kt)("p",null,"The ",(0,r.kt)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.kt)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.kt)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.kt)("p",null,"This query is equivalent to the following ",(0,r.kt)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.kt)("div",{class:"alert alert--info"},(0,r.kt)("p",null,"If you are used to ",(0,r.kt)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.kt)("code",null,"Product")," class is part of your ",(0,r.kt)("i",null,"domain"),"."),(0,r.kt)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.kt)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.kt)("p",null,"If you feel that GraphQL annotations do not belong to the domain, or if you cannot modify the class directly (maybe because it is part of a third party library), there is another way to create types without annotating the domain class. We will explore that in the next chapter.")))}d.isMDXComponent=!0},1410:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/fa41c0e9.5f4be9b5.js b/assets/js/fa41c0e9.1288cce7.js similarity index 99% rename from assets/js/fa41c0e9.5f4be9b5.js rename to assets/js/fa41c0e9.1288cce7.js index c28e99870e..44180e8390 100644 --- a/assets/js/fa41c0e9.5f4be9b5.js +++ b/assets/js/fa41c0e9.1288cce7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9307],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},6366:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-4.2/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.2/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/4.2/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/type-mapping.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-4.2/docs",previous:{title:"Mutations",permalink:"/docs/4.2/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.2/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.2/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.2/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9307],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),p=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,p.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>T});var a=n(7462),p=n(7294),l=n(6010),r=n(2466),s=n(6550),i=n(1980),u=n(7392),o=n(12);function c(e){return function(e){return p.Children.map(e,(e=>{if(!e||(0,p.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:p}}=e;return{value:t,label:n,attributes:a,default:p}}))}function m(e){const{values:t,children:n}=e;return(0,p.useMemo)((()=>{const e=t??c(n);return function(e){const t=(0,u.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function d(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,i._X)(l),(0,p.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!d({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[i,u]=h({queryString:n,groupId:a}),[c,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,o.Nk)(n);return[a,(0,p.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),g=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{g&&s(g)}),[g]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),y(e)}),[u,y,l]),tabValues:l}}var g=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function k(e){let{className:t,block:n,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.o5)(),m=e=>{const t=e.currentTarget,n=o.indexOf(t),a=u[n].value;a!==s&&(c(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const n=o.indexOf(e.currentTarget)+1;t=o[n]??o[0];break}case"ArrowLeft":{const n=o.indexOf(e.currentTarget)-1;t=o[n]??o[o.length-1];break}}t?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return p.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>o.push(e),onKeyDown:d,onClick:m},r,{className:(0,l.Z)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===t})}),n??t)})))}function b(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,p.cloneElement)(e,{className:"margin-top--md"}):null}return p.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,p.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function v(e){const t=y(e);return p.createElement("div",{className:(0,l.Z)("tabs-container",f.tabList)},p.createElement(k,(0,a.Z)({},e,t)),p.createElement(b,(0,a.Z)({},e,t)))}function T(e){const t=(0,g.Z)();return p.createElement(v,(0,a.Z)({key:String(t)},e))}},6366:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>i,default:()=>h,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var a=n(7462),p=(n(7294),n(3905)),l=(n(1839),n(4866)),r=n(5162);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-4.2/type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/versioned_docs/version-4.2/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/4.2/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/type-mapping.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"version-4.2/docs",previous:{title:"Mutations",permalink:"/docs/4.2/mutations"},next:{title:"Autowiring services",permalink:"/docs/4.2/autowiring"}},o={},c=[{value:"Scalar mapping",id:"scalar-mapping",level:2},{value:"Class mapping",id:"class-mapping",level:2},{value:"Array mapping",id:"array-mapping",level:2},{value:"ID mapping",id:"id-mapping",level:2},{value:"Force the outputType",id:"force-the-outputtype",level:3},{value:"ID class",id:"id-class",level:3},{value:"Date mapping",id:"date-mapping",level:2},{value:"Union types",id:"union-types",level:2},{value:"Enum types",id:"enum-types",level:2},{value:"Deprecation of fields",id:"deprecation-of-fields",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],m={toc:c},d="wrapper";function h(e){let{components:t,...n}=e;return(0,p.kt)(d,(0,a.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,p.kt)("p",null,"As explained in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.2/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.kt)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.kt)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.kt)("ul",null,(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"string")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"int")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"bool")),(0,p.kt)("li",{parentName:"ul"},(0,p.kt)("inlineCode",{parentName:"li"},"float"))),(0,p.kt)("p",null,"For instance:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n #[Query]\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello ' . $name;\n }\n}\n")))),(0,p.kt)("h2",{id:"class-mapping"},"Class mapping"),(0,p.kt)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.kt)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass Product\n{\n // ...\n\n #[Field]\n public function getName(): string\n {\n return $this->name;\n }\n\n #[Field]\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n */\n public function getPrice(): ?float\n {\n return $this->price;\n }\n}\n")))),(0,p.kt)("p",null,(0,p.kt)("strong",{parentName:"p"},"Note:")," The GraphQL output type name generated by GraphQLite is equal to the class name of the PHP class. So if your\nPHP class is ",(0,p.kt)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.kt)("p",null,'In case you have several types with the same class name in different namespaces, you will face a naming collision.\nHopefully, you can force the name of the GraphQL output type using the "name" attribute:'),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.kt)("div",{class:"alert alert--info"},"You can also put a ",(0,p.kt)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.kt)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.kt)("h2",{id:"array-mapping"},"Array mapping"),(0,p.kt)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.kt)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[] <=== we specify that the array is an array of User objects.\n */\n#[Query]\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[] <=== we specify that the array is an array of User objects.\n */\npublic function users(int $limit, int $offset): array\n{\n // Some code that returns an array of "users".\n}\n')))),(0,p.kt)("h2",{id:"id-mapping"},"ID mapping"),(0,p.kt)("p",null,"GraphQL comes with a native ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.kt)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.kt)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.kt)("p",null,"Using the ",(0,p.kt)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.kt)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.kt)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.kt)("p",null,"You can learn more about forcing output types in the ",(0,p.kt)("a",{parentName:"p",href:"/docs/4.2/custom-types"},"custom types section"),"."),(0,p.kt)("h3",{id:"id-class"},"ID class"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Field\n */\npublic function getId(): ID\n{\n // ...\n}\n")))),(0,p.kt)("p",null,"Note that you can also use the ",(0,p.kt)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Mutation]\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n/**\n * @Mutation\n */\npublic function save(ID $id, string $name): Product\n{\n // ...\n}\n")))),(0,p.kt)("h2",{id:"date-mapping"},"Date mapping"),(0,p.kt)("p",null,"Out of the box, GraphQL does not have a ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.kt)("p",null,"When used as an output type, ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.kt)("p",null,"The ",(0,p.kt)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.kt)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.kt)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.kt)("div",{class:"alert alert--danger"},"PHP ",(0,p.kt)("code",null,"DateTime")," type is not supported."),(0,p.kt)("h2",{id:"union-types"},"Union types"),(0,p.kt)("p",null,"You can create a GraphQL union type ",(0,p.kt)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.kt)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Company|Contact <== can return a company OR a contact.\n */\n#[Query]\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n"))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Company|Contact <== can return a company OR a contact.\n */\npublic function companyOrContact(int $id)\n{\n // Some code that returns a company or a contact.\n}\n")))),(0,p.kt)("h2",{id:"enum-types"},"Enum types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,"PHP has no native support for enum types. Hopefully, there are a number of PHP libraries that emulate enums in PHP.\nThe most commonly used library is ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.kt)("p",null,"You will first need to install ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.kt)("p",null,"Now, any class extending the ",(0,p.kt)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @return User[]\n */\n#[Query]\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"use MyCLabs\\Enum\\Enum;\n\nclass StatusEnum extends Enum\n{\n private const ON = 'on';\n private const OFF = 'off';\n private const PENDING = 'pending';\n}\n")),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'/**\n * @Query\n * @return User[]\n */\npublic function users(StatusEnum $status): array\n{\n if ($status == StatusEnum::ON()) {\n // Note that the "magic" ON() method returns an instance of the StatusEnum class.\n // Also, note that we are comparing this instance using "==" (using "===" would fail as we have 2 different instances here)\n // ...\n }\n // ...\n}\n')))),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.kt)("p",null,"By default, the name of the GraphQL enum type will be the name of the class. If you have a naming conflict (two classes\nthat live in different namespaces with the same class name), you can solve it using the ",(0,p.kt)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.kt)(l.Z,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.kt)(r.Z,{value:"php8",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n#[EnumType(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.kt)(r.Z,{value:"php7",mdxType:"TabItem"},(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\EnumType;\n\n/**\n * @EnumType(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.kt)("div",{class:"alert alert--warning"},'GraphQLite must be able to find all the classes extending the "MyCLabs\\Enum" class in your project. By default, GraphQLite will look for "Enum" classes in the namespaces declared for the types. For this reason, ',(0,p.kt)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.kt)("div",{class:"alert alert--info"},'There are many enumeration library in PHP and you might be using another library. If you want to add support for your own library, this is not extremely difficult to do. You need to register a custom "RootTypeMapper" with GraphQLite. You can learn more about ',(0,p.kt)("em",null,"type mappers")," in the ",(0,p.kt)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.kt)("a",{href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/MyCLabsEnumTypeMapper.php"},"copy/paste and adapt the root type mapper used for myclabs/php-enum"),"."),(0,p.kt)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.kt)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Entities;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Field;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type()\n */\nclass Product\n{\n // ...\n\n /**\n * @Field()\n */\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @Field()\n * @deprecated use field `name` instead\n */\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.kt)("p",null,"This will add the ",(0,p.kt)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.kt)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.kt)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.kt)("inlineCode",{parentName:"p"},"deprecationReason")," field in an introspection query. Fields marked as deprecated can still be queried, but will be returned in an introspection query only if ",(0,p.kt)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.kt)("inlineCode",{parentName:"p"},"true"),"."),(0,p.kt)("pre",null,(0,p.kt)("code",{parentName:"pre",className:"language-graphql"},'query {\n __type(name: "Product") {\n\ufffc fields(includeDeprecated: true) {\n\ufffc name\n\ufffc isDeprecated\n\ufffc deprecationReason\n\ufffc }\n\ufffc }\n}\n')),(0,p.kt)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.kt)("small",null,"Available in GraphQLite 4.0+"),(0,p.kt)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.kt)("p",null,"If you need more types, you can check the ",(0,p.kt)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-misc-types"},"GraphQLite Misc. Types library"),".\nIt adds support for more scalar types out of the box in GraphQLite."),(0,p.kt)("p",null,"Or if you have some special needs, ",(0,p.kt)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/fe153c07.80aa14ce.js b/assets/js/fe153c07.c1c80911.js similarity index 98% rename from assets/js/fe153c07.80aa14ce.js rename to assets/js/fe153c07.c1c80911.js index ed419c7777..1dcdf25d97 100644 --- a/assets/js/fe153c07.80aa14ce.js +++ b/assets/js/fe153c07.c1c80911.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2192],{122:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var r=a(7462),t=(a(7294),a(3905));a(1839);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,l={unversionedId:"other-frameworks",id:"version-3.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-3.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/3.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/other_frameworks.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1705957091,formattedLastUpdatedAt:"Jan 22, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-3.0/docs",previous:{title:"Universal service providers",permalink:"/docs/3.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/3.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Minimal example",id:"minimal-example",level:2},{value:"Advanced example",id:"advanced-example",level:2}],c={toc:p},u="wrapper";function h(e){let{components:n,...o}=e;return(0,t.kt)(u,(0,r.Z)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.kt)("p",null,"If you are using ",(0,t.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.kt)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.kt)("h2",{id:"installation"},"Installation"),(0,t.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.kt)("h2",{id:"requirements"},"Requirements"),(0,t.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.kt)("ul",null,(0,t.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.kt)("p",null,"GraphQLite relies on the ",(0,t.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and there is a ",(0,t.kt)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,t.kt)("h2",{id:"integration"},"Integration"),(0,t.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,t.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,t.kt)("p",null,"You can now use this schema with ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.kt)("p",null,"The ",(0,t.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n")),(0,t.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,t.kt)("p",null,"The smallest working example using no framework is:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, null, $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,t.kt)("h2",{id:"advanced-example"},"Advanced example"),(0,t.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library.\nBy chance, it plays well with PSR-7 requests and there is a PSR-15 middleware available."),(0,t.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.kt)("ul",null,(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-7 server"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"phps-cans/psr7-middleware-graphql")," to route PSR-7 requests to the GraphQL engine"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"composer.json")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^3",\n "phps-cans/psr7-middleware-graphql": "^0.2",\n "middlewares/payload": "^2.1",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"index.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.kt)("p",null,"Here we are initializing a Zend ",(0,t.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"config/container.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n // JsonPayload converts JSON body into a parser PHP array.\n $pipe->pipe(new JsonPayload());\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n return new WebonyxGraphqlMiddleware(\n $container->get(StandardServer::class),\n new ResponseFactory(),\n new StreamFactory()\n );\n },\n StandardServer::class => function(ContainerInterface $container) {\n return new StandardServer([\n 'schema' => $container->get(Schema::class)\n ]);\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,t.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"config/container.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,t.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.kt)("p",null,(0,t.kt)("img",{src:a(1410).Z,width:"1132",height:"352"})))}h.isMDXComponent=!0},1410:(e,n,a)=>{a.d(n,{Z:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2192],{122:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var r=a(7462),t=(a(7294),a(3905));a(1839);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,l={unversionedId:"other-frameworks",id:"version-3.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-3.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/3.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/other_frameworks.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1706561127,formattedLastUpdatedAt:"Jan 29, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-3.0/docs",previous:{title:"Universal service providers",permalink:"/docs/3.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/3.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"Minimal example",id:"minimal-example",level:2},{value:"Advanced example",id:"advanced-example",level:2}],c={toc:p},u="wrapper";function h(e){let{components:n,...o}=e;return(0,t.kt)(u,(0,r.Z)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.kt)("p",null,"If you are using ",(0,t.kt)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.kt)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.kt)("h2",{id:"installation"},"Installation"),(0,t.kt)("p",null,"Open a terminal in your current project directory and run:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.kt)("h2",{id:"requirements"},"Requirements"),(0,t.kt)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.kt)("ul",null,(0,t.kt)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.kt)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.kt)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.kt)("p",null,"GraphQLite relies on the ",(0,t.kt)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/"},"webonyx/graphql-php")," library internally.\nThis library plays well with PSR-7 requests and there is a ",(0,t.kt)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,t.kt)("h2",{id:"integration"},"Integration"),(0,t.kt)("p",null,"Webonyx/graphql-php library requires a ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/schema/"},"Schema")," in order to resolve\nGraphQL queries. We provide a ",(0,t.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n// $cache is a PSR-16 compatible cache\n// $container is a PSR-11 compatible container\n$factory = new SchemaFactory($cache, $container);\n$factory->addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n")),(0,t.kt)("p",null,"You can now use this schema with ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.kt)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.kt)("p",null,"The ",(0,t.kt)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the @Logged annotations).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the @Right annotations).\n$factory->setAuthorizationService(new VoidAuthorizationService());\n// Change the naming convention of GraphQL types globally.\n$factory->setNamingStrategy(new NamingStrategy());\n// Add a custom type mapper.\n$factory->addTypeMapper($typeMapper);\n// Add custom options to the Webonyx underlying Schema.\n$factory->setSchemaConfig($schemaConfig);\n")),(0,t.kt)("h2",{id:"minimal-example"},"Minimal example"),(0,t.kt)("p",null,"The smallest working example using no framework is:"),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"addControllerNamespace('App\\\\Controllers\\\\')\n ->addTypeNamespace('App\\\\');\n\n$schema = $factory->createSchema();\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\n$result = GraphQL::executeQuery($schema, $query, null, null, $variableValues);\n$output = $result->toArray();\n\nheader('Content-Type: application/json');\necho json_encode($output);\n")),(0,t.kt)("h2",{id:"advanced-example"},"Advanced example"),(0,t.kt)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.kt)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library.\nBy chance, it plays well with PSR-7 requests and there is a PSR-15 middleware available."),(0,t.kt)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.kt)("ul",null,(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-7 server"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"phps-cans/psr7-middleware-graphql")," to route PSR-7 requests to the GraphQL engine"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.kt)("li",{parentName:"ul"},(0,t.kt)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.kt)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"composer.json")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-json"},'{\n "autoload": {\n "psr-4": {\n "App\\\\": "src/"\n }\n },\n "require": {\n "thecodingmachine/graphqlite": "^3",\n "phps-cans/psr7-middleware-graphql": "^0.2",\n "middlewares/payload": "^2.1",\n "zendframework/zend-diactoros": "^2",\n "zendframework/zend-stratigility": "^3",\n "zendframework/zend-httphandlerrunner": "^1.0",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"index.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.kt)("p",null,"Here we are initializing a Zend ",(0,t.kt)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.kt)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.kt)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"config/container.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"}," function(ContainerInterface $container) {\n $pipe = new MiddlewarePipe();\n // JsonPayload converts JSON body into a parser PHP array.\n $pipe->pipe(new JsonPayload());\n $pipe->pipe($container->get(WebonyxGraphqlMiddleware::class));\n return $pipe;\n },\n // The WebonyxGraphqlMiddleware is a PSR-15 compatible\n // middleware that exposes Webonyx schemas.\n WebonyxGraphqlMiddleware::class => function(ContainerInterface $container) {\n return new WebonyxGraphqlMiddleware(\n $container->get(StandardServer::class),\n new ResponseFactory(),\n new StreamFactory()\n );\n },\n StandardServer::class => function(ContainerInterface $container) {\n return new StandardServer([\n 'schema' => $container->get(Schema::class)\n ]);\n },\n CacheInterface::class => function() {\n return new ApcuCache();\n },\n Schema::class => function(ContainerInterface $container) {\n // The magic happens here. We create a schema using GraphQLite SchemaFactory.\n $factory = new SchemaFactory($container->get(CacheInterface::class), $container);\n $factory->addControllerNamespace('App\\\\Controllers\\\\');\n $factory->addTypeNamespace('App\\\\');\n return $factory->createSchema();\n }\n]);\n")),(0,t.kt)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.kt)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.kt)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controllers;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\nclass MyController\n{\n /**\n * @Query\n */\n public function hello(string $name): string\n {\n return 'Hello '.$name;\n }\n}\n")),(0,t.kt)("p",null,(0,t.kt)("strong",{parentName:"p"},"config/container.php")),(0,t.kt)("pre",null,(0,t.kt)("code",{parentName:"pre",className:"language-php"},"use App\\Controllers\\MyController;\n\nreturn new Picotainer([\n // ...\n\n // We declare the controller in the container.\n MyController::class => function() {\n return new MyController();\n },\n]);\n")),(0,t.kt)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.kt)("p",null,(0,t.kt)("img",{src:a(1410).Z,width:"1132",height:"352"})))}h.isMDXComponent=!0},1410:(e,n,a)=>{a.d(n,{Z:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.7a4bcef9.js b/assets/js/runtime~main.c2ee611b.js similarity index 72% rename from assets/js/runtime~main.7a4bcef9.js rename to assets/js/runtime~main.c2ee611b.js index 40468fc4c7..5dc5f6c9b1 100644 --- a/assets/js/runtime~main.7a4bcef9.js +++ b/assets/js/runtime~main.c2ee611b.js @@ -1 +1 @@ -(()=>{"use strict";var e,a,c,f,d={},b={};function r(e){var a=b[e];if(void 0!==a)return a.exports;var c=b[e]={exports:{}};return d[e].call(c.exports,c,c.exports,r),c.exports}r.m=d,e=[],r.O=(a,c,f,d)=>{if(!c){var b=1/0;for(i=0;i=d)&&Object.keys(r.O).every((e=>r.O[e](c[o])))?c.splice(o--,1):(t=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[c,f,d]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var d=Object.create(null);r.r(d);var b={};a=a||[null,c({}),c([]),c(c)];for(var t=2&f&&e;"object"==typeof t&&!~a.indexOf(t);t=c(t))Object.getOwnPropertyNames(t).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,r.d(d,b),d},r.d=(e,a)=>{for(var c in a)r.o(a,c)&&!r.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,c)=>(r.f[c](e,a),a)),[])),r.u=e=>"assets/js/"+({45:"c329487f",53:"935f2afb",66:"e1b8bb84",67:"59b1a96c",120:"07c49ebd",152:"ba7653ad",153:"e5d7b215",169:"9279cea7",186:"1ba75d10",222:"346bcb92",228:"eca0cf35",242:"e196b408",251:"4e1a0951",254:"d49884c9",288:"cc1c02fe",306:"18d6c9c9",314:"beccb025",439:"3d2d0a86",473:"54c144e4",523:"cc1f18af",529:"61595218",562:"b0ed7ea5",593:"b8487569",630:"bf2a5963",634:"a1e3d512",635:"1428bdad",650:"78619623",678:"e91daeb9",680:"f7c03581",742:"6c124661",755:"02c5a8b1",766:"8f967659",772:"843ebfb4",781:"0db959c8",905:"5e21a9be",917:"ca36df4d",924:"8299d165",947:"e7672013",963:"bcc01c83",1012:"cd25a595",1021:"029c6d75",1126:"d9523c62",1173:"bd2c4a98",1239:"c5fa393d",1293:"9d336ee4",1326:"58e6b30f",1327:"d6b4b60c",1330:"7e507331",1333:"0ef60658",1396:"8d81badd",1407:"9953ecde",1427:"d4c8693b",1434:"24aca886",1449:"0fad1f8b",1464:"07666c14",1471:"2355609d",1506:"61c7d915",1569:"a264d631",1571:"5d7590c2",1606:"96877411",1627:"509d2004",1640:"26a27afb",1684:"d7067606",1692:"d8037f4c",1760:"cc08685c",1820:"8f7fa040",1886:"b94a1068",1905:"5ec7a7fe",1939:"b4657038",1977:"28c12eaf",1989:"c0fa6485",2020:"2014e4e3",2021:"7b54f5d5",2037:"579cc8d4",2080:"623b6c78",2117:"ae0a12ed",2157:"69f2ab1f",2192:"fe153c07",2196:"23f642f2",2272:"606959d6",2380:"cb01db44",2415:"612b773e",2446:"58d52345",2447:"e4c5fdc3",2495:"1f5e9707",2499:"a3a193a6",2521:"50122f86",2523:"dbf2bcb3",2535:"ece9cf29",2545:"7515d7ec",2559:"aa52484c",2583:"27258a7d",2612:"4d68b066",2650:"05e8cfc0",2733:"21a7a3b0",2767:"e38ecde0",2808:"b9d6d6e5",2827:"bcb6471f",2835:"6c14a231",2850:"e806c7bf",2885:"64947e00",2888:"c8bdc4df",2905:"f5b0a435",2923:"1e6ec01e",2935:"dab32d56",2946:"1b1927f4",2978:"2bbfc5d5",2998:"b7442939",3019:"e2e51976",3021:"366cfce3",3024:"0a57d896",3049:"e6858589",3059:"48fde361",3087:"c007fb39",3096:"394f3211",3100:"3d0eb74d",3173:"5ececfab",3189:"079b0d3e",3205:"24ac61c7",3229:"89cae3a7",3230:"d4a334ea",3236:"31b4e903",3239:"1e7fe27e",3287:"27e787ca",3312:"5fa4a5b6",3343:"01fe3043",3355:"9206a32f",3368:"741df2ae",3445:"aa5b6080",3497:"fa1dd05c",3534:"9664ee55",3545:"a30fd8ca",3567:"4f59166d",3597:"ed0c0463",3618:"b06c439f",3668:"e617c97b",3679:"e688cd7e",3699:"a9bc4f03",3709:"03abab96",3725:"a99e9943",3742:"bb5ef1b7",3755:"102de343",3769:"89ed63c8",3771:"471c3e37",3772:"18100524",3852:"72d0dc3a",3874:"32562f03",4009:"07623f9a",4041:"b5d32d98",4060:"673df5d6",4072:"1e138b9d",4076:"23794275",4100:"4f6c3156",4168:"a95c9e82",4195:"c4f5d8e4",4196:"08fe23a4",4211:"29a6c1ba",4235:"9749ab4a",4243:"e5d0e3cb",4265:"c4d37b36",4274:"f9511b3d",4280:"4e73bd72",4317:"a55b0daf",4367:"21cde469",4369:"ac8293fa",4374:"2ef99682",4446:"bb9fe7c3",4466:"e45c611c",4499:"a23a5b68",4519:"6d89025c",4584:"5945e8b0",4623:"b42f5805",4626:"eb333c39",4630:"a7159008",4688:"e63ebe23",4690:"75cc8326",4692:"6c6ce37c",4716:"6cfcfcfb",4735:"1d703573",4754:"a13f3cdc",4762:"4dd5816e",4773:"38317547",4866:"976f6afc",4868:"0e5befdb",4877:"a2d3d8d2",4948:"7afb60b1",5073:"c953ec08",5075:"aa675676",5091:"4d00e03a",5138:"57f5c28c",5207:"16017aa6",5231:"2e301473",5235:"71a56230",5244:"0cb7e976",5259:"5792f9ba",5307:"85339969",5314:"90e0b7fd",5320:"077a13b8",5325:"528fe65e",5403:"f2710c27",5505:"b6a6a31f",5515:"2e25c87f",5521:"13b4aeb1",5544:"4aab8b8c",5574:"c7e7ae18",5593:"e29eb381",5676:"d3540d59",5722:"c1fe0282",5745:"c275698c",5775:"107b7a36",5780:"e7ffb4b4",5795:"9073923c",5811:"756c6ac7",5813:"1f5af0f2",5820:"aebf35b6",5904:"1891fd2b",6005:"d07ad772",6031:"b103c05a",6107:"379bfe51",6130:"0343976d",6178:"136c1ee9",6259:"4a2da18c",6313:"68b7d615",6317:"56af72f6",6357:"a27f6be0",6364:"f9063551",6390:"7bf967bc",6409:"610e7425",6463:"55c77f1e",6489:"947f2c39",6516:"c933a311",6527:"7ee46e43",6555:"6ad31330",6561:"64536e1a",6564:"78da31a1",6595:"0fd21208",6596:"4a07aaf0",6722:"767c28af",6724:"4a060504",6769:"85c72337",6786:"30940d42",6868:"9bd507da",6902:"82395e72",6904:"400ddbbb",6929:"b5d0ac54",6956:"77cdcd82",6972:"bdb33130",6978:"8f7abfe1",7022:"2d4548df",7040:"17518879",7046:"2b26025e",7099:"74383bd8",7110:"23a8ac29",7121:"60d99771",7128:"085c135f",7162:"d589d3a7",7172:"8bf32d27",7178:"1aa05129",7276:"a28aff23",7294:"766e1cc8",7304:"0d7bb119",7334:"05fed6b1",7336:"5a9b411c",7337:"1edb88e5",7403:"bda39da3",7441:"cd30f404",7456:"36ddade1",7472:"107d11ee",7500:"3f944aba",7517:"f07f4757",7539:"a0bf4a5f",7582:"acbaac14",7622:"0db009bb",7711:"be1f0304",7794:"1e2c5f46",7870:"6efd6ec9",7918:"17896441",7920:"1a4e3797",7925:"5e352ef4",7959:"5ffc8074",7967:"1ea13486",7971:"e126d786",7990:"b2d9540a",7991:"6fe30f11",8037:"4d049718",8079:"b4aea2ce",8091:"7c27e34c",8100:"4c7f7507",8110:"652c74f1",8123:"504e6c2d",8165:"c3701568",8197:"2f36012a",8198:"4bdafdff",8223:"1520c72c",8270:"b9ea999a",8299:"4dfeb783",8334:"3b486936",8337:"eec7caa6",8348:"29cf2ad6",8368:"38cf1c7a",8369:"db6a6f31",8410:"0df2ba32",8447:"21637dff",8475:"4f30448a",8577:"f94b062c",8584:"56279b5e",8592:"common",8593:"0370fbfb",8612:"a320b509",8627:"8913b51a",8691:"8c95fc16",8702:"143f7888",8734:"8f951ce3",8752:"617523b3",8757:"26662da3",8773:"242d99d9",8835:"d4446569",8842:"f48e2589",8845:"d8ff000f",8854:"f309eabc",8929:"a16ee953",8931:"16565e6a",8932:"e347e63a",9001:"9f0ecd2e",9108:"cd699560",9136:"b26a5b84",9137:"565a5567",9212:"cddcd4e6",9226:"22e1e32f",9238:"7e63a40e",9271:"822cd419",9293:"4f4b6633",9297:"c69dda99",9307:"fa41c0e9",9327:"f4e1d1ba",9360:"9d9f8394",9368:"820db038",9422:"95576100",9462:"7d4976a8",9506:"54ca8693",9507:"b35d1284",9510:"d74b5642",9514:"1be78505",9549:"c7a4caa1",9580:"2d02c83c",9661:"263ebc7a",9701:"859fcda7",9711:"caa79efa",9722:"eaa287f0",9752:"354a9b78",9780:"8b6bafea",9811:"c10d4a63",9816:"b370b50c",9817:"ce95b17c",9862:"f9af357c",9872:"9000b231",9999:"d6188fd4"}[e]||e)+"."+{45:"4e1c634c",53:"646fbf80",66:"a3131c7f",67:"c2d309fb",120:"337a9957",152:"f135875a",153:"3c0d792a",169:"37d66749",186:"a69e3319",222:"39f9f3c7",228:"5a0afeae",242:"e6ac88af",251:"93fffe13",254:"a42f768a",288:"f473a573",306:"c281afcc",314:"097798c3",439:"4d7f4391",473:"1036bcef",523:"052fec8e",529:"81593eed",562:"5f3eee2b",593:"14aa5627",630:"5bb02ebe",634:"3c41b541",635:"43320636",650:"4b050134",678:"4c4cd16d",680:"d7cc737a",742:"f907a4c2",755:"f63b8f0a",766:"c22094f1",772:"3e27a84c",781:"6a4091ca",905:"98348313",917:"484ffd6d",924:"1e2f56c7",947:"23ce00f7",963:"1f12eb44",1012:"4e9d497f",1021:"f1bed900",1126:"4e46fc76",1173:"9d486e84",1239:"e88c7eac",1293:"f08b914d",1326:"796c7df7",1327:"4544dd32",1330:"20797d63",1333:"e92e1537",1396:"bf29df04",1407:"0c20885c",1426:"f97ca384",1427:"1dade46a",1434:"ea81c85e",1449:"03072e36",1464:"ebf949d4",1471:"2cd9bbbe",1506:"8b573ca5",1569:"f792823f",1571:"8e1fd956",1606:"6d0c752f",1627:"1e0ef8f6",1640:"853eb61b",1684:"e545a270",1692:"406c5fa5",1760:"cbfca237",1820:"e17cd78a",1886:"6e820e03",1905:"04316e40",1939:"7b635e9e",1977:"c4469c40",1989:"7219bd0c",2020:"a034f37a",2021:"5c60c0d3",2037:"fbcdc4ed",2080:"87ac2c9d",2117:"244e5058",2157:"4b6d8226",2192:"80aa14ce",2196:"8187351e",2272:"d3f9b660",2380:"d54c1a9c",2415:"08c521a0",2446:"8cf47ddc",2447:"2dfa0c08",2495:"8f8569d1",2499:"7e8710f4",2521:"1190b66f",2523:"ba6e8806",2535:"725eb00a",2545:"83073378",2559:"8eb1f6e7",2583:"d3f067f0",2612:"6a49e0b5",2650:"b6e1e919",2733:"60047475",2767:"d1a75bc4",2808:"7b7005ce",2827:"96899bc0",2835:"c405675e",2850:"aacdb54b",2885:"9d587f96",2888:"fd752015",2905:"61ff95b6",2923:"0a3b2b97",2935:"6bb178d7",2946:"f12b39fa",2978:"428785b5",2998:"6c0bd9aa",3019:"420e29b9",3021:"266ad45e",3024:"96ab7e2e",3049:"718aeb82",3059:"a1aa5712",3087:"06be5372",3096:"3e6aed2c",3100:"262e46a4",3173:"2c36e31a",3189:"0ae9d1bd",3205:"dda86a3c",3229:"629174eb",3230:"f251dda6",3236:"e5a1f7bc",3239:"182e7367",3287:"298b86e9",3312:"efc20e96",3343:"54b21c3a",3355:"b2bca24e",3368:"fdebd9e2",3445:"0c74d9f2",3497:"5c0314a3",3534:"6f31d682",3545:"dfc6df95",3567:"ca2e7dd1",3597:"5d6c04b1",3618:"d5f1c676",3668:"902973d6",3679:"fccecb47",3699:"1c9d5a72",3709:"bb40fac9",3725:"1db41608",3742:"b95a59ce",3755:"9511b5c5",3769:"09d04037",3771:"0598913d",3772:"d27c0f7e",3852:"9ea56172",3874:"ca3e9559",4009:"ebdfb4d1",4041:"85cad965",4060:"8b8c55e3",4072:"cec67549",4076:"393c831b",4100:"12ca5576",4168:"6c5dc87f",4195:"fa80792d",4196:"b4d430d0",4211:"5d0cc3a8",4235:"401fd048",4243:"ab31c48d",4265:"ecc9e476",4274:"b64acb7b",4280:"2972a3d8",4317:"fb56f0b7",4367:"284b5d64",4369:"7512ae64",4374:"0371e183",4446:"b1275489",4466:"d5d420c8",4499:"de412bf7",4519:"fc927e7c",4584:"419e3a48",4623:"957ee956",4626:"4fed5623",4630:"433262c0",4688:"1bae7062",4690:"940f7845",4692:"16a084ae",4716:"3d2ef2b8",4735:"7c629ab0",4754:"37d31e6a",4762:"e078b8af",4773:"969710aa",4866:"b31f2cb2",4868:"caccf97e",4877:"13c6fb19",4948:"c6cd6970",4972:"dc728d36",5073:"2ec7b349",5075:"72889597",5091:"d6388d9e",5138:"df5990bb",5207:"3cc39c32",5231:"f7d5e22d",5235:"e92f3cd7",5244:"546f70c1",5259:"1f9fbaa4",5307:"8e38e48e",5314:"b7ab9344",5320:"dc86dbd0",5325:"0256e3c1",5403:"65bf6004",5505:"fcb3b0f8",5515:"4b68e812",5521:"62d51a95",5544:"65c7aad0",5574:"733b58c5",5593:"c2d22e4a",5676:"05e6d0e3",5722:"8ee4eca6",5745:"d89cb04a",5775:"7ecba4f1",5780:"8656b35a",5795:"3b388fc3",5811:"24bcb393",5813:"57438961",5820:"129545d5",5904:"69638c22",6005:"03548c0a",6031:"cf4673ae",6107:"3040a372",6130:"b45455bc",6178:"8a420157",6259:"112fae41",6313:"f0c191ec",6317:"9aa66707",6357:"1422b8c7",6364:"9c8bf406",6390:"be2f05d3",6409:"edff6221",6463:"8b4e549d",6489:"2d271b64",6516:"f4497fb8",6527:"8b5fcb11",6555:"e03970f0",6561:"4db27fae",6564:"6cdc06aa",6595:"9194365d",6596:"f104366d",6722:"c728cdd1",6724:"298cb183",6769:"b88b2fa9",6786:"134f49ec",6868:"48d97c2b",6902:"008a12a5",6904:"72daa855",6929:"2a7c4b12",6945:"29c43de0",6956:"eccf4431",6972:"e3e2ea1c",6978:"577c9821",7022:"052db814",7040:"4da6c2ee",7046:"a6ff5151",7099:"e8d0f541",7110:"afac6f0e",7121:"c95dbd1c",7128:"d10ad352",7162:"f4e2e0db",7172:"0974ffeb",7178:"97a1b6e7",7276:"a01aef11",7294:"a67bce13",7304:"b55f86b3",7334:"696ddfac",7336:"21031480",7337:"566a704c",7403:"7ccd6c95",7441:"68d7e3a8",7456:"0575f8ab",7472:"67dc97d7",7500:"9bb9b1a0",7517:"7a9be42a",7539:"c74b5b59",7582:"a33203d5",7622:"7ccddee0",7711:"a75227bc",7794:"360bac5c",7870:"367be157",7918:"4eaedc42",7920:"aef3ce1d",7925:"9b70e54f",7959:"ba853ab9",7967:"0b572550",7971:"195c05fa",7990:"ae7f82b4",7991:"05f9db0c",8037:"71949449",8079:"c2a236ba",8091:"44e8bebb",8100:"b955a503",8110:"311657a5",8123:"ef45043a",8165:"ddede7ed",8197:"46661587",8198:"fe870ace",8223:"cb9f2c31",8270:"69e00773",8299:"22a2b26a",8334:"d0e8621f",8337:"77f86541",8348:"e212db87",8368:"facab26b",8369:"6111f0aa",8410:"6358bf74",8447:"8465a7b0",8475:"ff7b6a26",8577:"d8b886a7",8584:"681e0b3f",8592:"5cbcf52c",8593:"479939cf",8612:"adb1eb4e",8627:"cb8bac65",8691:"69a5ba73",8702:"10d803c7",8734:"74067c36",8752:"ffbea4c0",8757:"7da932f7",8773:"10285b77",8835:"9f545396",8842:"0060b545",8845:"f23621b2",8854:"bdafe4fb",8894:"143a3960",8929:"e022575c",8931:"521f71eb",8932:"6ded22d4",9001:"4ce3b9ac",9108:"0331ffa8",9136:"9b387ff5",9137:"bc14bb1d",9212:"416c328f",9226:"1f2952ae",9238:"8447f445",9271:"9209f1be",9293:"4ded7e42",9297:"c192c448",9307:"5f4be9b5",9327:"10e90bde",9360:"98f72146",9368:"2357f1b3",9422:"7f157755",9462:"6c553529",9506:"d25d41a5",9507:"1a39394f",9510:"a9ae03d1",9514:"f457d75f",9549:"691e6048",9580:"16fd8047",9661:"704a41b0",9701:"77d853b7",9711:"6c43f4db",9722:"d2a25c10",9752:"d904d69b",9780:"26fff7e6",9811:"4adfd255",9816:"90bde699",9817:"f4c63794",9862:"12894983",9872:"daf1ecbd",9999:"741060a1"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),f={},r.l=(e,a,c,d)=>{if(f[e])f[e].push(a);else{var b,t;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(l);var d=f[e];if(delete f[e],b.parentNode&&b.parentNode.removeChild(b),d&&d.forEach((e=>e(c))),a)return a(c)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=u.bind(null,b.onerror),b.onload=u.bind(null,b.onload),t&&document.head.appendChild(b)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/",r.gca=function(e){return e={17518879:"7040",17896441:"7918",18100524:"3772",23794275:"4076",38317547:"4773",61595218:"529",78619623:"650",85339969:"5307",95576100:"9422",96877411:"1606",c329487f:"45","935f2afb":"53",e1b8bb84:"66","59b1a96c":"67","07c49ebd":"120",ba7653ad:"152",e5d7b215:"153","9279cea7":"169","1ba75d10":"186","346bcb92":"222",eca0cf35:"228",e196b408:"242","4e1a0951":"251",d49884c9:"254",cc1c02fe:"288","18d6c9c9":"306",beccb025:"314","3d2d0a86":"439","54c144e4":"473",cc1f18af:"523",b0ed7ea5:"562",b8487569:"593",bf2a5963:"630",a1e3d512:"634","1428bdad":"635",e91daeb9:"678",f7c03581:"680","6c124661":"742","02c5a8b1":"755","8f967659":"766","843ebfb4":"772","0db959c8":"781","5e21a9be":"905",ca36df4d:"917","8299d165":"924",e7672013:"947",bcc01c83:"963",cd25a595:"1012","029c6d75":"1021",d9523c62:"1126",bd2c4a98:"1173",c5fa393d:"1239","9d336ee4":"1293","58e6b30f":"1326",d6b4b60c:"1327","7e507331":"1330","0ef60658":"1333","8d81badd":"1396","9953ecde":"1407",d4c8693b:"1427","24aca886":"1434","0fad1f8b":"1449","07666c14":"1464","2355609d":"1471","61c7d915":"1506",a264d631:"1569","5d7590c2":"1571","509d2004":"1627","26a27afb":"1640",d7067606:"1684",d8037f4c:"1692",cc08685c:"1760","8f7fa040":"1820",b94a1068:"1886","5ec7a7fe":"1905",b4657038:"1939","28c12eaf":"1977",c0fa6485:"1989","2014e4e3":"2020","7b54f5d5":"2021","579cc8d4":"2037","623b6c78":"2080",ae0a12ed:"2117","69f2ab1f":"2157",fe153c07:"2192","23f642f2":"2196","606959d6":"2272",cb01db44:"2380","612b773e":"2415","58d52345":"2446",e4c5fdc3:"2447","1f5e9707":"2495",a3a193a6:"2499","50122f86":"2521",dbf2bcb3:"2523",ece9cf29:"2535","7515d7ec":"2545",aa52484c:"2559","27258a7d":"2583","4d68b066":"2612","05e8cfc0":"2650","21a7a3b0":"2733",e38ecde0:"2767",b9d6d6e5:"2808",bcb6471f:"2827","6c14a231":"2835",e806c7bf:"2850","64947e00":"2885",c8bdc4df:"2888",f5b0a435:"2905","1e6ec01e":"2923",dab32d56:"2935","1b1927f4":"2946","2bbfc5d5":"2978",b7442939:"2998",e2e51976:"3019","366cfce3":"3021","0a57d896":"3024",e6858589:"3049","48fde361":"3059",c007fb39:"3087","394f3211":"3096","3d0eb74d":"3100","5ececfab":"3173","079b0d3e":"3189","24ac61c7":"3205","89cae3a7":"3229",d4a334ea:"3230","31b4e903":"3236","1e7fe27e":"3239","27e787ca":"3287","5fa4a5b6":"3312","01fe3043":"3343","9206a32f":"3355","741df2ae":"3368",aa5b6080:"3445",fa1dd05c:"3497","9664ee55":"3534",a30fd8ca:"3545","4f59166d":"3567",ed0c0463:"3597",b06c439f:"3618",e617c97b:"3668",e688cd7e:"3679",a9bc4f03:"3699","03abab96":"3709",a99e9943:"3725",bb5ef1b7:"3742","102de343":"3755","89ed63c8":"3769","471c3e37":"3771","72d0dc3a":"3852","32562f03":"3874","07623f9a":"4009",b5d32d98:"4041","673df5d6":"4060","1e138b9d":"4072","4f6c3156":"4100",a95c9e82:"4168",c4f5d8e4:"4195","08fe23a4":"4196","29a6c1ba":"4211","9749ab4a":"4235",e5d0e3cb:"4243",c4d37b36:"4265",f9511b3d:"4274","4e73bd72":"4280",a55b0daf:"4317","21cde469":"4367",ac8293fa:"4369","2ef99682":"4374",bb9fe7c3:"4446",e45c611c:"4466",a23a5b68:"4499","6d89025c":"4519","5945e8b0":"4584",b42f5805:"4623",eb333c39:"4626",a7159008:"4630",e63ebe23:"4688","75cc8326":"4690","6c6ce37c":"4692","6cfcfcfb":"4716","1d703573":"4735",a13f3cdc:"4754","4dd5816e":"4762","976f6afc":"4866","0e5befdb":"4868",a2d3d8d2:"4877","7afb60b1":"4948",c953ec08:"5073",aa675676:"5075","4d00e03a":"5091","57f5c28c":"5138","16017aa6":"5207","2e301473":"5231","71a56230":"5235","0cb7e976":"5244","5792f9ba":"5259","90e0b7fd":"5314","077a13b8":"5320","528fe65e":"5325",f2710c27:"5403",b6a6a31f:"5505","2e25c87f":"5515","13b4aeb1":"5521","4aab8b8c":"5544",c7e7ae18:"5574",e29eb381:"5593",d3540d59:"5676",c1fe0282:"5722",c275698c:"5745","107b7a36":"5775",e7ffb4b4:"5780","9073923c":"5795","756c6ac7":"5811","1f5af0f2":"5813",aebf35b6:"5820","1891fd2b":"5904",d07ad772:"6005",b103c05a:"6031","379bfe51":"6107","0343976d":"6130","136c1ee9":"6178","4a2da18c":"6259","68b7d615":"6313","56af72f6":"6317",a27f6be0:"6357",f9063551:"6364","7bf967bc":"6390","610e7425":"6409","55c77f1e":"6463","947f2c39":"6489",c933a311:"6516","7ee46e43":"6527","6ad31330":"6555","64536e1a":"6561","78da31a1":"6564","0fd21208":"6595","4a07aaf0":"6596","767c28af":"6722","4a060504":"6724","85c72337":"6769","30940d42":"6786","9bd507da":"6868","82395e72":"6902","400ddbbb":"6904",b5d0ac54:"6929","77cdcd82":"6956",bdb33130:"6972","8f7abfe1":"6978","2d4548df":"7022","2b26025e":"7046","74383bd8":"7099","23a8ac29":"7110","60d99771":"7121","085c135f":"7128",d589d3a7:"7162","8bf32d27":"7172","1aa05129":"7178",a28aff23:"7276","766e1cc8":"7294","0d7bb119":"7304","05fed6b1":"7334","5a9b411c":"7336","1edb88e5":"7337",bda39da3:"7403",cd30f404:"7441","36ddade1":"7456","107d11ee":"7472","3f944aba":"7500",f07f4757:"7517",a0bf4a5f:"7539",acbaac14:"7582","0db009bb":"7622",be1f0304:"7711","1e2c5f46":"7794","6efd6ec9":"7870","1a4e3797":"7920","5e352ef4":"7925","5ffc8074":"7959","1ea13486":"7967",e126d786:"7971",b2d9540a:"7990","6fe30f11":"7991","4d049718":"8037",b4aea2ce:"8079","7c27e34c":"8091","4c7f7507":"8100","652c74f1":"8110","504e6c2d":"8123",c3701568:"8165","2f36012a":"8197","4bdafdff":"8198","1520c72c":"8223",b9ea999a:"8270","4dfeb783":"8299","3b486936":"8334",eec7caa6:"8337","29cf2ad6":"8348","38cf1c7a":"8368",db6a6f31:"8369","0df2ba32":"8410","21637dff":"8447","4f30448a":"8475",f94b062c:"8577","56279b5e":"8584",common:"8592","0370fbfb":"8593",a320b509:"8612","8913b51a":"8627","8c95fc16":"8691","143f7888":"8702","8f951ce3":"8734","617523b3":"8752","26662da3":"8757","242d99d9":"8773",d4446569:"8835",f48e2589:"8842",d8ff000f:"8845",f309eabc:"8854",a16ee953:"8929","16565e6a":"8931",e347e63a:"8932","9f0ecd2e":"9001",cd699560:"9108",b26a5b84:"9136","565a5567":"9137",cddcd4e6:"9212","22e1e32f":"9226","7e63a40e":"9238","822cd419":"9271","4f4b6633":"9293",c69dda99:"9297",fa41c0e9:"9307",f4e1d1ba:"9327","9d9f8394":"9360","820db038":"9368","7d4976a8":"9462","54ca8693":"9506",b35d1284:"9507",d74b5642:"9510","1be78505":"9514",c7a4caa1:"9549","2d02c83c":"9580","263ebc7a":"9661","859fcda7":"9701",caa79efa:"9711",eaa287f0:"9722","354a9b78":"9752","8b6bafea":"9780",c10d4a63:"9811",b370b50c:"9816",ce95b17c:"9817",f9af357c:"9862","9000b231":"9872",d6188fd4:"9999"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(a,c)=>{var f=r.o(e,a)?e[a]:void 0;if(0!==f)if(f)c.push(f[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var d=new Promise(((c,d)=>f=e[a]=[c,d]));c.push(f[2]=d);var b=r.p+r.u(a),t=new Error;r.l(b,(c=>{if(r.o(e,a)&&(0!==(f=e[a])&&(e[a]=void 0),f)){var d=c&&("load"===c.type?"missing":c.type),b=c&&c.target&&c.target.src;t.message="Loading chunk "+a+" failed.\n("+d+": "+b+")",t.name="ChunkLoadError",t.type=d,t.request=b,f[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,c)=>{var f,d,b=c[0],t=c[1],o=c[2],n=0;if(b.some((a=>0!==e[a]))){for(f in t)r.o(t,f)&&(r.m[f]=t[f]);if(o)var i=o(r)}for(a&&a(c);n{"use strict";var e,a,c,f,d={},b={};function r(e){var a=b[e];if(void 0!==a)return a.exports;var c=b[e]={exports:{}};return d[e].call(c.exports,c,c.exports,r),c.exports}r.m=d,e=[],r.O=(a,c,f,d)=>{if(!c){var b=1/0;for(i=0;i=d)&&Object.keys(r.O).every((e=>r.O[e](c[o])))?c.splice(o--,1):(t=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[c,f,d]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var d=Object.create(null);r.r(d);var b={};a=a||[null,c({}),c([]),c(c)];for(var t=2&f&&e;"object"==typeof t&&!~a.indexOf(t);t=c(t))Object.getOwnPropertyNames(t).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,r.d(d,b),d},r.d=(e,a)=>{for(var c in a)r.o(a,c)&&!r.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,c)=>(r.f[c](e,a),a)),[])),r.u=e=>"assets/js/"+({45:"c329487f",53:"935f2afb",66:"e1b8bb84",67:"59b1a96c",120:"07c49ebd",152:"ba7653ad",153:"e5d7b215",169:"9279cea7",186:"1ba75d10",222:"346bcb92",228:"eca0cf35",242:"e196b408",251:"4e1a0951",254:"d49884c9",288:"cc1c02fe",306:"18d6c9c9",314:"beccb025",439:"3d2d0a86",473:"54c144e4",523:"cc1f18af",529:"61595218",562:"b0ed7ea5",593:"b8487569",630:"bf2a5963",634:"a1e3d512",635:"1428bdad",650:"78619623",678:"e91daeb9",680:"f7c03581",742:"6c124661",755:"02c5a8b1",766:"8f967659",772:"843ebfb4",781:"0db959c8",905:"5e21a9be",917:"ca36df4d",924:"8299d165",947:"e7672013",963:"bcc01c83",1012:"cd25a595",1021:"029c6d75",1126:"d9523c62",1173:"bd2c4a98",1239:"c5fa393d",1293:"9d336ee4",1326:"58e6b30f",1327:"d6b4b60c",1330:"7e507331",1333:"0ef60658",1396:"8d81badd",1407:"9953ecde",1427:"d4c8693b",1434:"24aca886",1449:"0fad1f8b",1464:"07666c14",1471:"2355609d",1506:"61c7d915",1569:"a264d631",1571:"5d7590c2",1606:"96877411",1627:"509d2004",1640:"26a27afb",1684:"d7067606",1692:"d8037f4c",1760:"cc08685c",1820:"8f7fa040",1886:"b94a1068",1905:"5ec7a7fe",1939:"b4657038",1977:"28c12eaf",1989:"c0fa6485",2020:"2014e4e3",2021:"7b54f5d5",2037:"579cc8d4",2080:"623b6c78",2117:"ae0a12ed",2157:"69f2ab1f",2192:"fe153c07",2196:"23f642f2",2272:"606959d6",2380:"cb01db44",2415:"612b773e",2446:"58d52345",2447:"e4c5fdc3",2495:"1f5e9707",2499:"a3a193a6",2521:"50122f86",2523:"dbf2bcb3",2535:"ece9cf29",2545:"7515d7ec",2559:"aa52484c",2583:"27258a7d",2612:"4d68b066",2650:"05e8cfc0",2733:"21a7a3b0",2767:"e38ecde0",2808:"b9d6d6e5",2827:"bcb6471f",2835:"6c14a231",2850:"e806c7bf",2885:"64947e00",2888:"c8bdc4df",2905:"f5b0a435",2923:"1e6ec01e",2935:"dab32d56",2946:"1b1927f4",2978:"2bbfc5d5",2998:"b7442939",3019:"e2e51976",3021:"366cfce3",3024:"0a57d896",3049:"e6858589",3059:"48fde361",3087:"c007fb39",3096:"394f3211",3100:"3d0eb74d",3173:"5ececfab",3189:"079b0d3e",3205:"24ac61c7",3229:"89cae3a7",3230:"d4a334ea",3236:"31b4e903",3239:"1e7fe27e",3287:"27e787ca",3312:"5fa4a5b6",3343:"01fe3043",3355:"9206a32f",3368:"741df2ae",3445:"aa5b6080",3497:"fa1dd05c",3534:"9664ee55",3545:"a30fd8ca",3567:"4f59166d",3597:"ed0c0463",3618:"b06c439f",3668:"e617c97b",3679:"e688cd7e",3699:"a9bc4f03",3709:"03abab96",3725:"a99e9943",3742:"bb5ef1b7",3755:"102de343",3769:"89ed63c8",3771:"471c3e37",3772:"18100524",3852:"72d0dc3a",3874:"32562f03",4009:"07623f9a",4041:"b5d32d98",4060:"673df5d6",4072:"1e138b9d",4076:"23794275",4100:"4f6c3156",4168:"a95c9e82",4195:"c4f5d8e4",4196:"08fe23a4",4211:"29a6c1ba",4235:"9749ab4a",4243:"e5d0e3cb",4265:"c4d37b36",4274:"f9511b3d",4280:"4e73bd72",4317:"a55b0daf",4367:"21cde469",4369:"ac8293fa",4374:"2ef99682",4446:"bb9fe7c3",4466:"e45c611c",4499:"a23a5b68",4519:"6d89025c",4584:"5945e8b0",4623:"b42f5805",4626:"eb333c39",4630:"a7159008",4688:"e63ebe23",4690:"75cc8326",4692:"6c6ce37c",4716:"6cfcfcfb",4735:"1d703573",4754:"a13f3cdc",4762:"4dd5816e",4773:"38317547",4866:"976f6afc",4868:"0e5befdb",4877:"a2d3d8d2",4948:"7afb60b1",5073:"c953ec08",5075:"aa675676",5091:"4d00e03a",5138:"57f5c28c",5207:"16017aa6",5231:"2e301473",5235:"71a56230",5244:"0cb7e976",5259:"5792f9ba",5307:"85339969",5314:"90e0b7fd",5320:"077a13b8",5325:"528fe65e",5403:"f2710c27",5505:"b6a6a31f",5515:"2e25c87f",5521:"13b4aeb1",5544:"4aab8b8c",5574:"c7e7ae18",5593:"e29eb381",5676:"d3540d59",5722:"c1fe0282",5745:"c275698c",5775:"107b7a36",5780:"e7ffb4b4",5795:"9073923c",5811:"756c6ac7",5813:"1f5af0f2",5820:"aebf35b6",5904:"1891fd2b",6005:"d07ad772",6031:"b103c05a",6107:"379bfe51",6130:"0343976d",6178:"136c1ee9",6259:"4a2da18c",6313:"68b7d615",6317:"56af72f6",6357:"a27f6be0",6364:"f9063551",6390:"7bf967bc",6409:"610e7425",6463:"55c77f1e",6489:"947f2c39",6516:"c933a311",6527:"7ee46e43",6555:"6ad31330",6561:"64536e1a",6564:"78da31a1",6595:"0fd21208",6596:"4a07aaf0",6722:"767c28af",6724:"4a060504",6769:"85c72337",6786:"30940d42",6868:"9bd507da",6902:"82395e72",6904:"400ddbbb",6929:"b5d0ac54",6956:"77cdcd82",6972:"bdb33130",6978:"8f7abfe1",7022:"2d4548df",7040:"17518879",7046:"2b26025e",7099:"74383bd8",7110:"23a8ac29",7121:"60d99771",7128:"085c135f",7162:"d589d3a7",7172:"8bf32d27",7178:"1aa05129",7276:"a28aff23",7294:"766e1cc8",7304:"0d7bb119",7334:"05fed6b1",7336:"5a9b411c",7337:"1edb88e5",7403:"bda39da3",7441:"cd30f404",7456:"36ddade1",7472:"107d11ee",7500:"3f944aba",7517:"f07f4757",7539:"a0bf4a5f",7582:"acbaac14",7622:"0db009bb",7711:"be1f0304",7794:"1e2c5f46",7870:"6efd6ec9",7918:"17896441",7920:"1a4e3797",7925:"5e352ef4",7959:"5ffc8074",7967:"1ea13486",7971:"e126d786",7990:"b2d9540a",7991:"6fe30f11",8037:"4d049718",8079:"b4aea2ce",8091:"7c27e34c",8100:"4c7f7507",8110:"652c74f1",8123:"504e6c2d",8165:"c3701568",8197:"2f36012a",8198:"4bdafdff",8223:"1520c72c",8270:"b9ea999a",8299:"4dfeb783",8334:"3b486936",8337:"eec7caa6",8348:"29cf2ad6",8368:"38cf1c7a",8369:"db6a6f31",8410:"0df2ba32",8447:"21637dff",8475:"4f30448a",8577:"f94b062c",8584:"56279b5e",8592:"common",8593:"0370fbfb",8612:"a320b509",8627:"8913b51a",8691:"8c95fc16",8702:"143f7888",8734:"8f951ce3",8752:"617523b3",8757:"26662da3",8773:"242d99d9",8835:"d4446569",8842:"f48e2589",8845:"d8ff000f",8854:"f309eabc",8929:"a16ee953",8931:"16565e6a",8932:"e347e63a",9001:"9f0ecd2e",9108:"cd699560",9136:"b26a5b84",9137:"565a5567",9212:"cddcd4e6",9226:"22e1e32f",9238:"7e63a40e",9271:"822cd419",9293:"4f4b6633",9297:"c69dda99",9307:"fa41c0e9",9327:"f4e1d1ba",9360:"9d9f8394",9368:"820db038",9422:"95576100",9462:"7d4976a8",9506:"54ca8693",9507:"b35d1284",9510:"d74b5642",9514:"1be78505",9549:"c7a4caa1",9580:"2d02c83c",9661:"263ebc7a",9701:"859fcda7",9711:"caa79efa",9722:"eaa287f0",9752:"354a9b78",9780:"8b6bafea",9811:"c10d4a63",9816:"b370b50c",9817:"ce95b17c",9862:"f9af357c",9872:"9000b231",9999:"d6188fd4"}[e]||e)+"."+{45:"7af6fe0e",53:"646fbf80",66:"d98e7215",67:"c4ae7fd3",120:"e45a8e99",152:"b15d10e5",153:"f6b6ec90",169:"909fcd8a",186:"3f051919",222:"95778f9b",228:"810abbea",242:"c5507d5e",251:"1f1b32c1",254:"ab0ad481",288:"a772bc02",306:"ad2e854a",314:"ac117a94",439:"cb6bfa21",473:"c2279d68",523:"c46f462f",529:"0e14427c",562:"d76a41ce",593:"9ec8cb9a",630:"5f2239f4",634:"c9753d80",635:"58de4f6f",650:"81477d8b",678:"0403b08d",680:"c8a60a0f",742:"4afbc706",755:"91aeeb5a",766:"e5513f88",772:"1adbb5cc",781:"8dedaa56",905:"9d203747",917:"627fff1b",924:"a0a27b49",947:"97c9e5e1",963:"41601842",1012:"f4210a8e",1021:"65a906c8",1126:"cbe8d3dd",1173:"7af535c4",1239:"3f51a552",1293:"43e96d65",1326:"448b537c",1327:"dd968bd2",1330:"79ffb9b6",1333:"a3f086b4",1396:"1daf10fc",1407:"dc002d88",1426:"f97ca384",1427:"f5b98357",1434:"cbe1384c",1449:"03072e36",1464:"fb1b640d",1471:"46e2b30f",1506:"398ed930",1569:"9a1b1bd1",1571:"a13f01b9",1606:"2895f908",1627:"3c2b48e1",1640:"24de608e",1684:"7c1d6410",1692:"0fe7cd3c",1760:"a7406d7b",1820:"c37651ec",1886:"c50458a0",1905:"a1f7d0fb",1939:"09de5a1b",1977:"144e51a7",1989:"9e1178ac",2020:"fb5e0b97",2021:"8c106400",2037:"c024d536",2080:"1c316b9c",2117:"a0896775",2157:"269ccd0b",2192:"c1c80911",2196:"a399885b",2272:"c1125b7a",2380:"b46217e8",2415:"d0b59610",2446:"1410724b",2447:"a81b7d1a",2495:"5c27d17d",2499:"9e84f3bc",2521:"37ed1b04",2523:"cae22b5f",2535:"3ee571cb",2545:"8a2a1484",2559:"6a6d21da",2583:"481f14b8",2612:"5650e6de",2650:"b86474cb",2733:"2c1a0984",2767:"d1a75bc4",2808:"145a6fb6",2827:"8fdff316",2835:"1bf3c0cf",2850:"4e7e4404",2885:"45a668db",2888:"34e19a51",2905:"b78baf4d",2923:"42b2995e",2935:"6bb178d7",2946:"573f9cb0",2978:"891ea6bc",2998:"5a65161b",3019:"19f28336",3021:"185a20a6",3024:"6c31eb99",3049:"d3810fdf",3059:"ffab8f86",3087:"9a2bad32",3096:"9412d7df",3100:"72c38bde",3173:"f2968018",3189:"d4aa9ead",3205:"ec9e739b",3229:"9aadef3c",3230:"f251dda6",3236:"1488d8a2",3239:"76635a46",3287:"298b86e9",3312:"9fc9d71c",3343:"3d1b7f71",3355:"5cb7cf65",3368:"49494839",3445:"d0411448",3497:"30a84796",3534:"057665d8",3545:"d5c8e65e",3567:"90f1a358",3597:"e4fbc445",3618:"eadb4bfa",3668:"198da7fd",3679:"ac81e355",3699:"40176044",3709:"fb3893ea",3725:"4187a1d0",3742:"ad212a40",3755:"dc005dfe",3769:"87fcb1a0",3771:"27163584",3772:"38c63d00",3852:"6b636748",3874:"ca3e9559",4009:"23924493",4041:"b700415a",4060:"54464c7c",4072:"cec67549",4076:"d9e24816",4100:"db0f9c03",4168:"953d011b",4195:"fa80792d",4196:"6a618c2f",4211:"b1fa9f48",4235:"869cf3a9",4243:"9aa24194",4265:"c99dbb44",4274:"67fd62ec",4280:"f90df4ab",4317:"6a64689e",4367:"b4e8e7ed",4369:"ebfb9f4e",4374:"67e711bf",4446:"fe9e89d6",4466:"13fab258",4499:"c894cd66",4519:"091b58f8",4584:"b16e6f0b",4623:"771e0d34",4626:"7bcf779f",4630:"433262c0",4688:"d16cff09",4690:"f6f786ec",4692:"18a34ffd",4716:"f22408b0",4735:"a109bf96",4754:"6f484099",4762:"0df8298c",4773:"062642d0",4866:"904f12c9",4868:"47cf4738",4877:"2daaa519",4948:"be1b28ca",4972:"dc728d36",5073:"450e2f30",5075:"ffcd78b5",5091:"437691d8",5138:"3f0e7ab5",5207:"8d532e45",5231:"0b12c408",5235:"fb833262",5244:"dc857927",5259:"7f08dd0b",5307:"507c1cb5",5314:"d0b658f7",5320:"575a51af",5325:"3280ecb1",5403:"25c40395",5505:"9deb08a6",5515:"616c2a7f",5521:"7a9401d1",5544:"4ce6ea9e",5574:"44f9933c",5593:"3bc795eb",5676:"85ed7083",5722:"eab02ae3",5745:"9344294b",5775:"47f69cda",5780:"12bd1fa6",5795:"4d345ff0",5811:"1fe3fef5",5813:"44486702",5820:"50727791",5904:"3626160c",6005:"dc754465",6031:"0fbb9d7e",6107:"699532e6",6130:"e81aa885",6178:"40baeed2",6259:"8c8cf89a",6313:"1a23ca24",6317:"c4e69c59",6357:"5a1578c0",6364:"32b958d4",6390:"ab7cb5af",6409:"cf6abf89",6463:"c179ac78",6489:"6adad4d3",6516:"164393fe",6527:"9d672d82",6555:"26f70583",6561:"aab3dff8",6564:"ab83c85b",6595:"9945be0b",6596:"c8c241c7",6722:"a7e2b841",6724:"87c44a25",6769:"9f918097",6786:"47c1861a",6868:"6274f204",6902:"221b92eb",6904:"6dc8b14d",6929:"09e727dc",6945:"29c43de0",6956:"58364c16",6972:"3f6b3639",6978:"f46038e4",7022:"2d139f18",7040:"804a3db9",7046:"22ae6ab5",7099:"01881c20",7110:"2756a312",7121:"4901986b",7128:"eed3a49c",7162:"4dbb3b64",7172:"df6bbf23",7178:"bd36efa9",7276:"a8081c43",7294:"06c37046",7304:"f432e9d0",7334:"38feeb95",7336:"b408216a",7337:"5417dcb2",7403:"9feaa3b0",7441:"c89e8722",7456:"dec2ebb3",7472:"6c98fe0c",7500:"796d879a",7517:"22b41240",7539:"ed20eed6",7582:"924c3730",7622:"722111a0",7711:"09fe2006",7794:"a2a9a199",7870:"cf281cda",7918:"4eaedc42",7920:"1587bb31",7925:"0e87aed3",7959:"034c05bc",7967:"75b19a56",7971:"99a7c6b2",7990:"89e5221c",7991:"c0b06c25",8037:"4f1b4174",8079:"f5f04c00",8091:"318b2482",8100:"492c852a",8110:"c5d3d2e8",8123:"baf50a06",8165:"5549601e",8197:"b37caaa7",8198:"97cc0e41",8223:"cb9f2c31",8270:"55231b9f",8299:"a32bd5fa",8334:"8dc0317b",8337:"8b087ab1",8348:"57b90fab",8368:"e3aa5eda",8369:"c0058a7a",8410:"2ce34e95",8447:"c6ce2a3c",8475:"031bc330",8577:"8920a9cb",8584:"30fed670",8592:"5cbcf52c",8593:"11bb62db",8612:"0b11ed31",8627:"56bd279a",8691:"051526fe",8702:"252a04c0",8734:"8bd0aae6",8752:"fdc3aa9c",8757:"984614fe",8773:"a504c308",8835:"37e9c2d3",8842:"cd474b0d",8845:"cffb1b5a",8854:"486245e5",8894:"143a3960",8929:"cc3b8ffc",8931:"8efa5fde",8932:"68690188",9001:"d55ede3b",9108:"3905c5de",9136:"e5f8e8c1",9137:"88632e57",9212:"07845102",9226:"00eae62a",9238:"b7c16e86",9271:"9f2ee9d6",9293:"361110e8",9297:"16b6bf92",9307:"1288cce7",9327:"c968124d",9360:"3443ecf0",9368:"1ddc7111",9422:"0a64d2ef",9462:"6c553529",9506:"ca7ee31a",9507:"c69f3805",9510:"a9ae03d1",9514:"f457d75f",9549:"86241355",9580:"941e9cc8",9661:"ace1016a",9701:"7ee0c73a",9711:"1b7095a0",9722:"914edb1c",9752:"4a28b27c",9780:"bf2e59f2",9811:"b5502b9a",9816:"7fdfaa6f",9817:"850e0c56",9862:"323b5b1d",9872:"818ff52b",9999:"057acc4e"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),f={},r.l=(e,a,c,d)=>{if(f[e])f[e].push(a);else{var b,t;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(l);var d=f[e];if(delete f[e],b.parentNode&&b.parentNode.removeChild(b),d&&d.forEach((e=>e(c))),a)return a(c)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=u.bind(null,b.onerror),b.onload=u.bind(null,b.onload),t&&document.head.appendChild(b)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/",r.gca=function(e){return e={17518879:"7040",17896441:"7918",18100524:"3772",23794275:"4076",38317547:"4773",61595218:"529",78619623:"650",85339969:"5307",95576100:"9422",96877411:"1606",c329487f:"45","935f2afb":"53",e1b8bb84:"66","59b1a96c":"67","07c49ebd":"120",ba7653ad:"152",e5d7b215:"153","9279cea7":"169","1ba75d10":"186","346bcb92":"222",eca0cf35:"228",e196b408:"242","4e1a0951":"251",d49884c9:"254",cc1c02fe:"288","18d6c9c9":"306",beccb025:"314","3d2d0a86":"439","54c144e4":"473",cc1f18af:"523",b0ed7ea5:"562",b8487569:"593",bf2a5963:"630",a1e3d512:"634","1428bdad":"635",e91daeb9:"678",f7c03581:"680","6c124661":"742","02c5a8b1":"755","8f967659":"766","843ebfb4":"772","0db959c8":"781","5e21a9be":"905",ca36df4d:"917","8299d165":"924",e7672013:"947",bcc01c83:"963",cd25a595:"1012","029c6d75":"1021",d9523c62:"1126",bd2c4a98:"1173",c5fa393d:"1239","9d336ee4":"1293","58e6b30f":"1326",d6b4b60c:"1327","7e507331":"1330","0ef60658":"1333","8d81badd":"1396","9953ecde":"1407",d4c8693b:"1427","24aca886":"1434","0fad1f8b":"1449","07666c14":"1464","2355609d":"1471","61c7d915":"1506",a264d631:"1569","5d7590c2":"1571","509d2004":"1627","26a27afb":"1640",d7067606:"1684",d8037f4c:"1692",cc08685c:"1760","8f7fa040":"1820",b94a1068:"1886","5ec7a7fe":"1905",b4657038:"1939","28c12eaf":"1977",c0fa6485:"1989","2014e4e3":"2020","7b54f5d5":"2021","579cc8d4":"2037","623b6c78":"2080",ae0a12ed:"2117","69f2ab1f":"2157",fe153c07:"2192","23f642f2":"2196","606959d6":"2272",cb01db44:"2380","612b773e":"2415","58d52345":"2446",e4c5fdc3:"2447","1f5e9707":"2495",a3a193a6:"2499","50122f86":"2521",dbf2bcb3:"2523",ece9cf29:"2535","7515d7ec":"2545",aa52484c:"2559","27258a7d":"2583","4d68b066":"2612","05e8cfc0":"2650","21a7a3b0":"2733",e38ecde0:"2767",b9d6d6e5:"2808",bcb6471f:"2827","6c14a231":"2835",e806c7bf:"2850","64947e00":"2885",c8bdc4df:"2888",f5b0a435:"2905","1e6ec01e":"2923",dab32d56:"2935","1b1927f4":"2946","2bbfc5d5":"2978",b7442939:"2998",e2e51976:"3019","366cfce3":"3021","0a57d896":"3024",e6858589:"3049","48fde361":"3059",c007fb39:"3087","394f3211":"3096","3d0eb74d":"3100","5ececfab":"3173","079b0d3e":"3189","24ac61c7":"3205","89cae3a7":"3229",d4a334ea:"3230","31b4e903":"3236","1e7fe27e":"3239","27e787ca":"3287","5fa4a5b6":"3312","01fe3043":"3343","9206a32f":"3355","741df2ae":"3368",aa5b6080:"3445",fa1dd05c:"3497","9664ee55":"3534",a30fd8ca:"3545","4f59166d":"3567",ed0c0463:"3597",b06c439f:"3618",e617c97b:"3668",e688cd7e:"3679",a9bc4f03:"3699","03abab96":"3709",a99e9943:"3725",bb5ef1b7:"3742","102de343":"3755","89ed63c8":"3769","471c3e37":"3771","72d0dc3a":"3852","32562f03":"3874","07623f9a":"4009",b5d32d98:"4041","673df5d6":"4060","1e138b9d":"4072","4f6c3156":"4100",a95c9e82:"4168",c4f5d8e4:"4195","08fe23a4":"4196","29a6c1ba":"4211","9749ab4a":"4235",e5d0e3cb:"4243",c4d37b36:"4265",f9511b3d:"4274","4e73bd72":"4280",a55b0daf:"4317","21cde469":"4367",ac8293fa:"4369","2ef99682":"4374",bb9fe7c3:"4446",e45c611c:"4466",a23a5b68:"4499","6d89025c":"4519","5945e8b0":"4584",b42f5805:"4623",eb333c39:"4626",a7159008:"4630",e63ebe23:"4688","75cc8326":"4690","6c6ce37c":"4692","6cfcfcfb":"4716","1d703573":"4735",a13f3cdc:"4754","4dd5816e":"4762","976f6afc":"4866","0e5befdb":"4868",a2d3d8d2:"4877","7afb60b1":"4948",c953ec08:"5073",aa675676:"5075","4d00e03a":"5091","57f5c28c":"5138","16017aa6":"5207","2e301473":"5231","71a56230":"5235","0cb7e976":"5244","5792f9ba":"5259","90e0b7fd":"5314","077a13b8":"5320","528fe65e":"5325",f2710c27:"5403",b6a6a31f:"5505","2e25c87f":"5515","13b4aeb1":"5521","4aab8b8c":"5544",c7e7ae18:"5574",e29eb381:"5593",d3540d59:"5676",c1fe0282:"5722",c275698c:"5745","107b7a36":"5775",e7ffb4b4:"5780","9073923c":"5795","756c6ac7":"5811","1f5af0f2":"5813",aebf35b6:"5820","1891fd2b":"5904",d07ad772:"6005",b103c05a:"6031","379bfe51":"6107","0343976d":"6130","136c1ee9":"6178","4a2da18c":"6259","68b7d615":"6313","56af72f6":"6317",a27f6be0:"6357",f9063551:"6364","7bf967bc":"6390","610e7425":"6409","55c77f1e":"6463","947f2c39":"6489",c933a311:"6516","7ee46e43":"6527","6ad31330":"6555","64536e1a":"6561","78da31a1":"6564","0fd21208":"6595","4a07aaf0":"6596","767c28af":"6722","4a060504":"6724","85c72337":"6769","30940d42":"6786","9bd507da":"6868","82395e72":"6902","400ddbbb":"6904",b5d0ac54:"6929","77cdcd82":"6956",bdb33130:"6972","8f7abfe1":"6978","2d4548df":"7022","2b26025e":"7046","74383bd8":"7099","23a8ac29":"7110","60d99771":"7121","085c135f":"7128",d589d3a7:"7162","8bf32d27":"7172","1aa05129":"7178",a28aff23:"7276","766e1cc8":"7294","0d7bb119":"7304","05fed6b1":"7334","5a9b411c":"7336","1edb88e5":"7337",bda39da3:"7403",cd30f404:"7441","36ddade1":"7456","107d11ee":"7472","3f944aba":"7500",f07f4757:"7517",a0bf4a5f:"7539",acbaac14:"7582","0db009bb":"7622",be1f0304:"7711","1e2c5f46":"7794","6efd6ec9":"7870","1a4e3797":"7920","5e352ef4":"7925","5ffc8074":"7959","1ea13486":"7967",e126d786:"7971",b2d9540a:"7990","6fe30f11":"7991","4d049718":"8037",b4aea2ce:"8079","7c27e34c":"8091","4c7f7507":"8100","652c74f1":"8110","504e6c2d":"8123",c3701568:"8165","2f36012a":"8197","4bdafdff":"8198","1520c72c":"8223",b9ea999a:"8270","4dfeb783":"8299","3b486936":"8334",eec7caa6:"8337","29cf2ad6":"8348","38cf1c7a":"8368",db6a6f31:"8369","0df2ba32":"8410","21637dff":"8447","4f30448a":"8475",f94b062c:"8577","56279b5e":"8584",common:"8592","0370fbfb":"8593",a320b509:"8612","8913b51a":"8627","8c95fc16":"8691","143f7888":"8702","8f951ce3":"8734","617523b3":"8752","26662da3":"8757","242d99d9":"8773",d4446569:"8835",f48e2589:"8842",d8ff000f:"8845",f309eabc:"8854",a16ee953:"8929","16565e6a":"8931",e347e63a:"8932","9f0ecd2e":"9001",cd699560:"9108",b26a5b84:"9136","565a5567":"9137",cddcd4e6:"9212","22e1e32f":"9226","7e63a40e":"9238","822cd419":"9271","4f4b6633":"9293",c69dda99:"9297",fa41c0e9:"9307",f4e1d1ba:"9327","9d9f8394":"9360","820db038":"9368","7d4976a8":"9462","54ca8693":"9506",b35d1284:"9507",d74b5642:"9510","1be78505":"9514",c7a4caa1:"9549","2d02c83c":"9580","263ebc7a":"9661","859fcda7":"9701",caa79efa:"9711",eaa287f0:"9722","354a9b78":"9752","8b6bafea":"9780",c10d4a63:"9811",b370b50c:"9816",ce95b17c:"9817",f9af357c:"9862","9000b231":"9872",d6188fd4:"9999"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(a,c)=>{var f=r.o(e,a)?e[a]:void 0;if(0!==f)if(f)c.push(f[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var d=new Promise(((c,d)=>f=e[a]=[c,d]));c.push(f[2]=d);var b=r.p+r.u(a),t=new Error;r.l(b,(c=>{if(r.o(e,a)&&(0!==(f=e[a])&&(e[a]=void 0),f)){var d=c&&("load"===c.type?"missing":c.type),b=c&&c.target&&c.target.src;t.message="Loading chunk "+a+" failed.\n("+d+": "+b+")",t.name="ChunkLoadError",t.type=d,t.request=b,f[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,c)=>{var f,d,b=c[0],t=c[1],o=c[2],n=0;if(b.some((a=>0!==e[a]))){for(f in t)r.o(t,f)&&(r.m[f]=t[f]);if(o)var i=o(r)}for(a&&a(c);n